zoukankan      html  css  js  c++  java
  • go的变量redeclare的问题,golang的一个小坑

    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的请注意
  • 相关阅读:
    19. Remove Nth Node From End of List
    18. 4Sum
    16. 3Sum Closest
    15. 3Sum
    17. Letter Combinations of a Phone Number
    A Network-based End-to-End Trainable Task-oriented Dialogue System
    14. Longest Common Prefix
    36. Valid Sudoku
    29. Divide Two Integers
    32. Longest Valid Parentheses
  • 原文地址:https://www.cnblogs.com/liangDream/p/3909968.html
Copyright © 2011-2022 走看看