📅  最后修改于: 2023-12-03 14:59:01.846000             🧑  作者: Mango
Go programming language is a statically-typed programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson in 2007. One of the unique features of Go programming language is the use of ':=' operator to declare and assign variables in a single statement.
The ':=' operator is called the short variable declaration operator. It is a convenient way to declare and assign values to variables. Unlike the '=' operator, the ':=' operator infers the type of the variable from the assigned value.
Here is an example of how to use the ':=' operator:
package main
import "fmt"
func main() {
// declare and assign a string variable
s := "Hello, Gophers!"
// declare and assign an integer variable
i := 42
// declare and assign a boolean variable
b := true
fmt.Println(s, i, b)
}
The above code declares and assigns a string variable s
with the value "Hello, Gophers!", an integer variable i
with the value 42, and a boolean variable b
with the value true. Then, it prints the values of these variables to the console.
The output of the above code will be:
Hello, Gophers! 42 true
As you can see, the ':=' operator allows you to declare and assign variables in a single statement, making the code shorter and more readable.
In addition to the short variable declaration operator, Go programming language also has the regular variable declaration syntax using the '=' operator. The '=' operator requires you to explicitly state the data type of the declared variable.
Here is an example of how to use the '=' operator:
package main
import "fmt"
func main() {
// declare a string variable
var s string
// assign a value to the string variable
s = "Hello, Gophers!"
// declare an integer variable
var i int
// assign a value to the integer variable
i = 42
// declare a boolean variable
var b bool
// assign a value to the boolean variable
b = true
fmt.Println(s, i, b)
}
The above code achieves the same result as the previous code using the regular variable declaration syntax.
In conclusion, the ':=' operator is a unique feature of the Go programming language that allows you to declare and assign variables in a single statement. This makes the code shorter and more readable.