Menu
CoddyTech

Struct 값

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

JavaScript에서 객체를 할당하면 동일성이 공유되고, 객체 전개는 필드를 얕게 복사합니다. Go에서 구조체를 할당하면 이미 필드가 값으로 복사됩니다. 구조체를 복사한 뒤에도 포인터, 맵 또는 슬라이스 필드는 공유 데이터를 참조할 수 있습니다.

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

JavaScript 예제

const a={text:"old"};const b={...a};b.text="new";console.log(a.text,b.text);

소스 출력:

old new

Go 예제

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
challenge icon

챌린지

쉬움

내보낸 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)
}
quiz icon실력 점검

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

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

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