Menu
CoddyTech

구조체 값

Coddy의 GDScript 개발자를 위한 Go 코스 레슨. 48개 중 25번째.

GDScript 객체는 참조와 유사한 공유 정체성을 가지지만, Go 구조체는 대입할 때 복사됩니다. 구조체를 복사하면 스칼라 필드는 분리되지만, 공유 포인터, 맵 또는 슬라이스의 기반 저장 공간은 계속 공유될 수 있습니다. 객체 대입을 구조체 복사로 취급하는 대신, 독립적인 스칼라 상태를 모델링하려면 별도의 GDScript 인스턴스를 생성하세요.

구조체는 이름이 지정된 필드를 고정된 타입과 함께 묶습니다. 키가 지정된 리터럴은 설정할 필드의 이름을 지정하며, 생략된 필드에는 제로 값이 할당됩니다. 구조체 값을 대입하면 복사되지만, 구조체 내부의 포인터, 슬라이스 및 맵 필드는 여전히 공유 데이터를 참조할 수 있습니다.

GDScript 예제

extends Node

class TextLabel:
	extends RefCounted
	var text: String
	func _init(value: String) -> void:
		text=value

func _ready() -> void:
	var a: TextLabel = TextLabel.new("old")
	var b: TextLabel = TextLabel.new(a.text)
	b.text="new"
	prints(a.text,b.text)

출력 결과:

old new

Go 예제

package main
import ("fmt")
type TextLabel struct { Text string }
func main(){a:=TextLabel{Text:"old"}
b:=a
b.Text="new"
fmt.Println(a.Text,b.Text)}

Go 출력 결과:

old new
challenge icon

챌린지

쉬움

내보내기되는 int 필드 Left와 Right를 가진 Pair를 정의하세요. Solve는 두 필드의 합을 반환합니다. 입력값 x와 y는 각각 별도의 줄에 입력됩니다.

선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필수 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력에는 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)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

GDScript 개발자를 위한 Go의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러