티스토리 뷰

go

GO 구조체(struct)

까오기 2024. 7. 11. 16:59

Go 언어에서 구조체(struct)는 여러 필드를 그룹화하여 복합 데이터를 정의하는 사용자 정의 타입입니다. 구조체는 객체지향 프로그래밍의 클래스와 유사한 개념으로, 관련된 데이터와 메서드를 하나의 단위로 묶어 관리할 수 있습니다.

구조체 정의

구조체를 정의할 때는 struct 키워드를 사용합니다. 구조체는 하나 이상의 필드로 구성되며, 각 필드는 이름과 타입을 가집니다.

type Person struct {
    Name string
    Age  int
}

위 예제에서는 Person이라는 구조체 타입을 정의하였으며, Name과 Age라는 두 개의 필드를 가지고 있습니다.

구조체 초기화

구조체를 초기화하고 사용하는 방법에는 여러 가지가 있습니다.

1. 필드 이름을 명시하여 초기화

p := Person{
    Name: "Alice",
    Age:  30,
}

2. 필드 순서에 따라 초기화

p := Person{"Alice", 30}

3. 개별 필드에 값을 할당

var p Person
p.Name = "Alice"
p.Age = 30

구조체 필드 접근

구조체 필드에 접근할 때는 점(.) 연산자를 사용합니다.

fmt.Println(p.Name) // 출력: Alice
fmt.Println(p.Age)  // 출력: 30

구조체 메서드

구조체는 메서드를 가질 수 있습니다. 메서드는 특정 타입(주로 구조체)에 대해 정의된 함수입니다.

func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}

위 예제에서 Greet 메서드는 Person 타입의 값을 리시버로 받습니다. 이를 통해 Person 구조체와 관련된 동작을 정의할 수 있습니다.

메서드를 호출할 때는 구조체 인스턴스를 통해 호출합니다.

p := Person{"Alice", 30}
fmt.Println(p.Greet()) // 출력: Hello, my name is Alice

예제: 구조체 사용

다음은 구조체를 정의하고 사용하는 예제입니다.

package main

import "fmt"

// 구조체 정의
type Person struct {
    Name string
    Age  int
}

// 구조체 메서드 정의
func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}

func main() {
    // 구조체 초기화
    p := Person{
        Name: "Alice",
        Age:  30,
    }

    // 필드 접근
    fmt.Println("Name:", p.Name) // 출력: Name: Alice
    fmt.Println("Age:", p.Age)   // 출력: Age: 30

    // 메서드 호출
    fmt.Println(p.Greet()) // 출력: Hello, my name is Alice
}

포인터 리시버

구조체 메서드를 정의할 때 값 리시버 대신 포인터 리시버를 사용할 수 있습니다. 포인터 리시버를 사용하면 메서드 내에서 구조체 필드를 수정할 수 있습니다.

func (p *Person) UpdateName(newName string) {
    p.Name = newName
}

func main() {
    p := Person{"Alice", 30}
    p.UpdateName("Bob")
    fmt.Println(p.Name) // 출력: Bob
}

위 예제에서 UpdateName 메서드는 Person 구조체의 포인터를 리시버로 받아서 Name 필드를 수정합니다.

구조체의 임베딩

Go에서는 구조체 임베딩을 통해 다른 구조체의 필드를 포함하고 재사용할 수 있습니다. 이는 상속과 비슷한 개념입니다.

type Employee struct {
    Person
    Position string
}

func main() {
    e := Employee{
        Person:   Person{Name: "Alice", Age: 30},
        Position: "Developer",
    }
    fmt.Println(e.Name) // 출력: Alice
    fmt.Println(e.Age)  // 출력: 30
    fmt.Println(e.Position) // 출력: Developer
}

위 예제에서 Employee 구조체는 Person 구조체를 임베딩하여 Name과 Age 필드를 상속받습니다. 이렇게 하면 구조체 간의 재사용성과 구성을 쉽게 할 수 있습니다.

이와 같이 Go 언어에서 구조체는 복잡한 데이터를 다루고, 관련 동작을 정의하며, 코드 재사용성을 높이는 데 중요한 역할을 합니다.

 

전체 예제 

package main

import "fmt"

// 구조체 정의
type Person struct {
	Name string
	Age  int
}

// 구조체 메서드 정의
func (p Person) Greet() string {
	return "Hello, my name is " + p.Name
}

func (p *Person) UpdateName(newName string) {
	p.Name = newName
}

type Employee struct {
	Person
	Position string
}

func main() {
	// 구조체 초기화
	p := Person{
		Name: "Alice",
		Age:  30,
	}

	// 필드 접근
	fmt.Println("Name:", p.Name) // 출력: Name: Alice
	fmt.Println("Age:", p.Age)   // 출력: Age: 30

	// 메서드 호출
	fmt.Println(p.Greet()) // 출력: Hello, my name is Alice

	p2 := Person{"Alice", 30}
	p2.UpdateName("Bob")
	fmt.Println(p2.Name) // 출력: Bob

	e := Employee{
		Person:   Person{Name: "Alice", Age: 30},
		Position: "Developer",
	}
	fmt.Println(e.Name)     // 출력: Alice
	fmt.Println(e.Age)      // 출력: 30
	fmt.Println(e.Position) // 출력: Developer
}

 

결과 

Name: Alice
Age: 30
Hello, my name is Alice
Bob
Alice
30
Developer

 

출처 : chatGPT

'go' 카테고리의 다른 글

Go 인터페이스  (0) 2024.07.11
Go 메서드(Method)  (0) 2024.07.11
Go 패키지  (0) 2024.07.11
Go 컬렉션  (0) 2024.07.11
Go 클로저(closure)  (0) 2024.07.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함