duanba8173 2019-03-27 21:14
浏览 35
已采纳

使用初始化器了解变量

I am learning the basics of go (golang).

I can't seem to wrap my head around how variables with initializers work.

package main

import "fmt"

var i, j int = 100000, 5

func main() {
    fmt.Println(j)
}

When i print out j i get 5 instead of 100000, why is that?

  • 写回答

2条回答 默认 最新

  • doudou521125 2019-03-27 21:24
    关注

    When initializing multiple variables they are initialized in the order in which they are passed.

    So if you are declaring first i then j, then the values 100000 then 5 are assigned in the same order.

    When you print j you will get 5 because it is the second variable and corresponds to the second value.

    This also applies to the same way that multiple variable returns work in go, example below, or working example here in the playground.

    func doStuff() (string, int) {
        red, five := "red", 5
        return red, five
    }
    

    See this helpful resource for more information on working with variables, and this from the Tour of Go on working with multiple variable returns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大