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
249 views
in Technique[技术] by (71.8m points)

go - why return &strut than return a ${name, 0}

code:

type account struct {
    owner   string
    balance int
}
func NewAccount(owner string) *account {
    account := account{owner: owner, balance: 0}
    return &account
}

question: Why NewAccount return value is &{name, 0} why not a memory address ?

question from:https://stackoverflow.com/questions/65650788/why-return-strut-than-return-a-name-0

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

1 Answer

0 votes
by (71.8m points)

That's the default fmt print format. See the section on verbs to understand how the change the format: https://golang.org/pkg/fmt/#hdr-Printing

fmt.Println(NewAccount("name"))
// output: &{name 0}
fmt.Printf("%p
", NewAccount("name"))
// output: 0xc00010c040

https://play.golang.org/p/I-EC_1yTqT-


Alternatively use the builtin print or println functions, but keep in mind that these are not guaranteed to stay in the language.

println(NewAccount("name"))
// output: 0xc0000a0f60

https://play.golang.org/p/bH97NGStYsi


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

...