dongliao3450 2016-05-03 14:53
浏览 46
已采纳

Go中的`fmt.Println`如何工作?

Have 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条回答 默认 最新

  • doutou3725 2016-05-03 15:07
    关注
    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色