Struct 값
Coddy의 Python 개발자를 위한 Go 코스 레슨. 48개 중 25번째.
Python 클래스 인스턴스는 대입할 때 일반적으로 동일한 객체를 참조하며, 데이터클래스도 대입 의미를 바꾸지 않습니다. Go 구조체를 대입하면 필드가 복사됩니다. 포인터, 맵 또는 슬라이스 필드 내부에서 참조하는 저장 공간은 복사 후에도 공유될 수 있습니다.
구조체는 이름이 지정된 필드와 고정된 타입을 하나로 묶습니다. 키를 지정하는 리터럴은 설정할 필드를 명시하며, 생략된 필드에는 영 값이 할당됩니다. 구조체 값을 대입하면 복사되지만, 구조체 내부의 포인터, 슬라이스 및 맵 필드는 여전히 공유 데이터를 참조할 수 있습니다.
Python 예제
from dataclasses import dataclass, replace
@dataclass
class Label:
text: str
a = Label("old")
b = replace(a)
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챌린지
쉬움내보낸 정수 필드 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)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Python 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러