Implementation details of fmt.Println in golang

雨燕双飞 提交于 2019-12-04 04:11:44

问题


Consider this code

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
 }

I have 2 questions

  1. Why I have to pass bigSum as reference (by using &) to get the correct answer, otherwise we'll get back an object?

  2. How does Println work in Go? I mean how does it know which format it should apply for different types?


回答1:


  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.


来源:https://stackoverflow.com/questions/37007494/implementation-details-of-fmt-println-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!