구조체와 인터페이스

Go Structs

Group related values into your own type with named fields.

  • 중급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Defining a struct
  • Fields and %+v
  • Structs are copied
User
Name"Ada"
Age37
Activetrue

Your own type with named fields

A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.

Fields are read and changed with a dot. %v prints the values and %+v adds the field names. Assigning a struct copies it, so changing guest does not change user. A struct can also be declared in place without a name.

핵심 포인트

  1. Fields are read and changed with a dot.
  2. %+v prints the field names too.
  3. Assigning a struct copies it.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import "fmt"

type User struct {
	Name   string
	Age    int
	Active bool
}

func main() {
	user := User{Name: "Ada", Age: 36, Active: true}
	user.Age++

	fmt.Println(user.Name, user.Age)
	fmt.Printf("%v\n%+v\n", user, user)

	guest := user // structs are copied on assignment
	guest.Name = "Guest"
	fmt.Println(user.Name, guest.Name)

	point := struct{ X, Y int }{3, 4}
	fmt.Println(point.X + point.Y)
}
이 예제의 실행 버튼 만들기 코드 실행 결과
Ada 37
{Ada 37 true}
{Name:Ada Age:37 Active:true}
Ada Guest
7

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지