• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go的变量redeclare的问题,golang的一个小坑

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

go的变量声明有几种方式:

1 通过关键字 var 进行声明

   例如:var i int   然后进行赋值操作 i = 5

2 最简单的,通过符号 := 进行声明和赋值

   例如: i:=5 golang会默认它的类型

下面看一段代码,我们先声明一个变量a,然后再重新声明变量a,b,在这个函数中,变量a被声明了2次,成为a的重声明(redeclare),执行结果为23

package main

import (

  "fmt"

)

func main(){

    a:=1

    a,b:=2,3

    fmt.Println(a,b)

}

精彩的部分来了,请看第二段代码

package main

import (

  "fmt"

)

type A struct{

 i int

}

func main(){

    testA:=&A{}

    testA.i=1

    testA.i,b:=2,3

    fmt.Println(testA.i,b)

}

我们定义了一个简单的结构体A,A中的成员变量为i,我们在testA.i,b:=2,3对成员变量进行了新的声明和赋值,执行会报错。

原因:这个问题Google上是有过讨论的

 Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
从go的spec看,redeclare是一个赋值,不是创建个新变量,为什么对于成员变量不可以,只能暂时理解成设计问题吧 
 
这里是一个小坑,玩golang的请注意

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go语言基础之结构体发布时间:2022-07-10
下一篇:
[Go]golang的接口合约发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap