구조체 값
Coddy의 Lua 개발자를 위한 Go 코스 레슨. 48개 중 25번째.
Lua 테이블 할당은 동일성을 공유하는 반면, Go 구조체 할당은 이름이 지정된 필드를 복사합니다. 새로운 Lua 테이블은 개별 스칼라 필드를 모델링할 수 있지만, 중첩된 테이블은 참조로 복사될 때 여전히 공유 상태로 유지됩니다. Go 구조체 역시 포인터, 맵 또는 슬라이스 필드를 통해 공유 저장소를 유지할 수 있습니다. 겉 복사(outer copy)와 깊은 복사(deep copy)를 구별하세요.
구조체는 고정된 타입을 가진 이름이 지정된 필드들을 그룹화합니다. 키 지정 리터럴은 설정되는 필드의 이름을 명시하며, 생략된 필드는 제로 값(zero value)을 받습니다. 할당은 구조체 값을 복사하지만, 내부의 포인터, 슬라이스 및 맵 필드는 여전히 공유 데이터를 참조할 수 있습니다.
Lua 예제
local a={text="old"}; local b={text=a.text}; b.text="new"; print(a.text.." "..b.text)
소스 출력:
old newGo 예제
package main
import ("fmt")
type Label struct { Text string }
func main(){a:=Label{Text:"old"}
b:=a
b.Text="new"
fmt.Println(a.Text,b.Text)}
Go 출력:
old new챌린지
쉬움내보내기된(exported) int 필드인 Left와 Right를 가진 Pair를 정의하세요. Solve는 이들의 합을 반환합니다. x와 y는 별도의 줄에 입력됩니다.
선언된 API를 구현하세요. 결과를 출력하지 않고 반환하세요. 드라이버는 필요한 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션 stdout은 JSON이 아닌 Go 대괄호 포맷팅을 사용합니다.
코드는 pair.go, exercise.go에 작성합니다. main.go는 제공된 입출력 코드를 포함하며 수정할 수 없습니다. 단일 package main을 유지하고, 두 번째 main을 추가하지 마세요.
직접 해보기
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
a1:=I(1); before1:=fmt.Sprint(a1)
p:=Pair{Left:4,Right:9}; q:=p; q.Left=0; must(p.Left==4 && p.Right==9,"struct value");
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Lua 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러