为什么使用简写语法来声明/初始化变量?

huangapple go评论68阅读模式
英文:

Why the shorthand syntax to declare/init variables?

问题

这两种变量声明/初始化的方式有什么区别吗?

package main

import "fmt"

func main() {
    var a = "I am a string"        // 声明 + 初始化(推断类型)
    fmt.Println(a)

    b := "I am a string"           // 声明 + 初始化(简化写法)
    fmt.Println(b)
}

我没有看出简化语法的附加价值,并且倾向于在我的代码中始终使用var语句以保持一致性。

英文:

Is there a difference between these 2 styles of variable declaration/initialization?

package main

import "fmt"

func main() {

 	var a = "I am a string"        // Declare + init (infer)
	fmt.Println(a)

    b := "I am a string"           // Declare + init (shorthand)
	fmt.Println(b)
}

I fail to see the added value of the shorthand syntax, and inclined to use the "var" statement for consistency throughout my code.

答案1

得分: 6

我总是尝试使用:=语法。当你需要重构代码时,它的好处是巨大的。

你不需要将变量的名称绑定到任何特定的类型,每当你改变右侧的类型时,变量会自动推断出新的类型。

英文:

I always try to use the := syntax. The benefit is huge when you need to Refactor code.

You are not binding the name of the variable to any particular type and any time you change the right hand side's type the variable would automatically infer the new type.

答案2

得分: 5

我只在必要时使用var关键字,比如:

1)全局变量

2)在if语句中,例如:

var err error
if x == nil {
    err = errors.New("x is nil")
} else if y == nil {
    err = errors.New("y is nil")
}

...

英文:

I only use var when necessary, like:

  1. global variables

  2. if statement like:

    var err error
    if x == nil {
    err = errors.New("x is nil")
    } else if y == nil {
    err = errors.New("y is nil")
    }

...

huangapple
  • 本文由 发表于 2014年7月18日 17:50:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/24822079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定