Gomt中fmt.Println的实现细节 [英] Implementation details of fmt.Println in golang

查看:152
本文介绍了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个问题

  1. 为什么我必须通过bigSum作为引用(通过使用&)来获得正确的答案,否则我们将取回一个对象?

  1. 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?

推荐答案

  1. Println确定该值是否实现Stringer接口.如果是这样,它将调用String()以获得格式化的值. big.Float为指针接收器实现了它,因此您必须传递一个引用.否则,Println将检测到它是一个结构,并使用反射来打印所有字段
  2. Go是开源的.您可以自己查看 https://golang.org/src/fmt/print.go?#L738它使用类型开关和反射.
  1. Println determines whether the value implements the Stringer interface. If it does then it will call the String() to get formatted value. big.Float implements it for pointer receiver so you have to pass a reference. Otherwise Println will detect that it's a struct and print all of it's fields using reflection
  2. 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的实现细节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆