Golang type embedding 에러 "cannot use promoted field {} in struct literal of type {}"

인문학적 개발자 늘한·2020년 10월 17일
0

Go lang

목록 보기
1/1
post-thumbnail

go 언어는 class 대신 구조체(struct) 를 사용합니다.
그렇다보니 다른 프로그래밍 언어의 class 처럼 상속을 처리하는 대신 embedding 이라는 방법을 이용합니다.

package main

import "fmt"

type Human struct {
	name string
	age  int
}

type Programmer struct {
	Human
	githubID string
}

func (h *Human) Hello() {
	fmt.Println(fmt.Sprintf("Hello, %s. You are %d years old.", h.name, h.age))
}

func main() {
	humanBeing := Human{name: "한결", age: 23}
	humanBeing.Hello()

	programmerBeing := Programmer{name: "늘한", age: 23, githubID: "Neulhan"}
	// cannot use promoted field {} in struct literal of type {}
}

다만 embedded 된 구조체에 있는 값을 embedding 된 구조체에서 선언을 할 때 입력하려고 하면 아래와 같은 오류가 발생합니다.

> go run main.go
# command-line-arguments
./main.go:27:32: cannot use promoted field Human.name in struct literal of type Programmer
./main.go:27:48: cannot use promoted field Human.age in struct literal of type Programmer

해결방법

이를 해결하기 위한 첫 번째 방법은 아래와 같이 embedded 되는 구조체를 새로 만들어서 넣어주는 방법입니다.

programmerBeing := Programmer{Human: Human{name: "해결책1", age: 23}, githubID: "Neulhan"}
programmerBeing.Hello()
> go run main.go
Hello, 한결. You are 23 years old.
Hello, 해결책1. You are 23 years old.

두 번째 방법은 Programmer 구조체를 선언만 해놓고 값을 이후에 각각 할당해주는 방법입니다.

var programmerBeing Programmer
programmerBeing.name = "해결책2"
programmerBeing.age = 23
programmerBeing.githubID = "Neulhan"
programmerBeing.Hello()
> go run main.go
Hello, 한결. You are 23 years old.
Hello, 해결책2. You are 23 years old.

애초에 golang이 struct를 직접 embedding 하는 것 보다 interface 를 이용하는 방법을 지향하고 있기도 하고, 객체지향형 프로그래밍 보다 함수형 프로그래밍에 가까운 성향 때문인지, 두 해결책 모두 뭔가 말끔하다는 생각이 들지는 않는 것 같습니다.
(해당 이슈도 아직 열려있는 상태)

reference

https://github.com/golang/go/issues/9859

profile
영어영문학과 출신의 개발자 늘한입니다. Python 을 좋아합니다.

0개의 댓글