本文介绍了Gomt中fmt.Println的实现细节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑此代码
import (
"fmt"
"math/big"
)
func main() {
var b1,b2,b3,bigSum big.Float
b1.SetFloat64(25.3)
b2.SetFloat64(76.2)
b1.SetFloat64(53.1)
bigSum.Add(&b1, &b2).Add(&b3, &bigSum)
fmt.Println(bigSum) // {53 0 0 1 false [9317046909104082944] 8}
fmt.Println(&bigSum) // 129.3
}
我有2个问题
-
为什么我必须通过
bigSum
作为引用(通过使用&
)来获得正确的答案,否则我们将取回一个对象?
Why I have to pass
bigSum
as reference (by using&
) to get the correct answer, otherwise we'll get back an object?
Println
在Go中如何工作?我的意思是它如何知道应将哪种格式应用于不同类型?
How does Println
work in Go? I mean how does it know which format it should apply for different types?
推荐答案
-
Println
确定该值是否实现Stringer
接口.如果是这样,它将调用String()
以获得格式化的值.big.Float
为指针接收器实现了它,因此您必须传递一个引用.否则,Println
将检测到它是一个结构,并使用反射来打印所有字段 - Go是开源的.您可以自己查看 https://golang.org/src/fmt/print.go?#L738它使用类型开关和反射.
Println
determines whether the value implements theStringer
interface. If it does then it will call theString()
to get formatted value.big.Float
implements it for pointer receiver so you have to pass a reference. OtherwisePrintln
will detect that it's a struct and print all of it's fields using reflection- Go is open sourced. You can see for yourself https://golang.org/src/fmt/print.go?#L738 It uses type switches and reflection.
这篇关于Gomt中fmt.Println的实现细节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!