英文:
Shortest way / Shorthand to declare variable in go
问题
我们可以使用以下语法来声明Go变量:
var num int
var str string
但是在Go中是否有任何简写方式来完成相同的操作?
例如,在Python中我们可以简单地这样做:
num = 13
strings = "Hello World"
甚至可以这样做:
num, strings = 13, "Hello World"
英文:
We can use the following syntax for go variable declaration
var num int
var str string
but is there any shorthand in go for doing the same thing?
for example we can do so in python simply saying:
num = 13
strings = "Hello World"
or even
num, strings = 13,"Hello World"
答案1
得分: 6
变量声明可以初始化多个变量:
var x, y float32 = -1, -2
或者(使用:=
的短变量声明)
i, j := 0, 10
所以这段代码可以正常工作:play.golang.org
package main
import "fmt"
func main() {
a, b := 1, "e"
fmt.Printf("Hello, playground %v %v", b, a)
}
输出结果:
Hello, playground e 1
英文:
The variable declaration can initialize multiple variables:
var x, y float32 = -1, -2
Or (short variable declaration with :=
)
i, j := 0, 10
So this would work: play.golang.org
package main
import "fmt"
func main() {
a, b := 1, "e"
fmt.Printf("Hello, playground %v %v", b, a)
}
Output:
Hello, playground e 1
答案2
得分: 1
:=
语法是 Go 语言中声明和初始化变量的简写方式。
例如:
要声明一个字符串变量 e
,我们可以简单地使用以下代码:
str := "Hello world"
英文:
The :=
syntax is shorthand for declaring and initializing a Go variable .
For example:
to declare e string var we can simple use
答案3
得分: 1
短变量声明
:= 运算符是短变量声明运算符。该运算符用于声明和初始化变量。
示例:
package main
import "fmt"
func main() {
firstName := "Joey"
fmt.Println(firstName)
}
变量类型并不重要,因为Go编译器能够根据你分配的值推导出类型。由于我们将一个字符串赋给了firstName,所以firstName被分配为字符串类型。
英文:
Short variable declarations
The := operator is the short variable declaration operator. This operator is used to both declare and initialize a variable.
package main
import "fmt"
func main() {
firstName := "Joey"
fmt.Println(firstName)
}
The variable type is not vital because the Go compiler is able to derive the type based on the value you have assigned. Since we are assigning a string to firstName, firstName is allocated as a variable type as string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论