상세 컨텐츠

본문 제목

28/2 Struct Pointer study

Go/Study record

by Gopythor 2022. 3. 1. 01:02

본문

728x90
반응형

Code

package main

import "fmt"

type Person struct {
    Address  string
    PostCode string
    JobType string
    Company string
}

type PersonBuilder struct {
    person *Person
}

func NewPersonBuilder() *PersonBuilder {

    return &PersonBuilder{&Person{}}
}

func main() {
    pb := NewPersonBuilder()        //&{0xc0000b6040}
    pd := &Person{"a", "b", "c", "d"}    //&{a b c d}
    fmt.Println(pb, pd)
}

Result

&{0xc0000b6040} &{a b c d}
  • pb has Person Pointer
  • pd has a,b,c,d values in person struct.
  • The fmt package uses reflection to print out values, and there is a specific case to print a pointer to a struct as &{Field Value}

Code for struct Pointer

fmt.Printf("&person is: %p\n", pd)

Result

&person is: 0xc0000bc080

https://go.dev/play/p/P2kMz-D1hsn

Refer

func main() {
    pb := NewPersonBuilder()
    fmt.Println(reflect.TypeOf(pb))        //*main.PersonBuilder
    fmt.Printf("pb: %[1]T %[1]p\n", pb)    //pb: *main.PersonBuilder 0xc0000ba018
    pd := &Person{"a", "b", "c", "d"}    //&{a b c d}
    fmt.Println(pb, pd)            //&{0xc0000bc040} &{a b c d}
}
728x90
반응형

관련글 더보기

댓글 영역