Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

go - Difference using pointer in struct fields

We can create structs in golang this way. Examples below: What are differences between these two?

// Usual way
type Employee struct {
    firstName string    `json:"name"`
    salary    int       `json:"salary"`
    fullTime  bool      `json:"fullTime"`
    projects  []Project `json:"projects"`
}

// Un-usal way with pointers
type Employee struct {
    firstName *string    `json:"name"`
    salary    *int       `json:"salary"`
    fullTime  *bool      `json:"fullTime"`
    projects  *[]Project `json:"projects"`
}

Are there any trade-offs like memory?

Update:

Assume below function:

// this function consumes MORE memory
func printEmployeeWithoutPointer(employee Employee) {
    // print here
}

// this function consumes LESS memory
func printEmployeeWithPointer(employee *Employee) {
    // print here
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...