乐闻世界logo
搜索文章和话题

What is the difference between and operators in go

4个答案

1
2
3
4

In Go, = and := are two distinct operators used for variable assignment, but they serve different purposes and contexts.

  • = is the assignment operator, used to assign a new value to an already declared variable. Before using =, the variable must already be declared. For example:
go
var x int x = 1 // Assigning value 1 to the declared variable x

In this example, x is first declared as an int type, and then = is used to assign the value 1 to x.

  • := is the short variable declaration operator, used to declare and initialize a variable simultaneously. Within a function, if you wish to declare a new local variable and assign it immediately, you can use := to do so. This eliminates the need for explicit type declaration, as Go automatically infers the variable type based on the expression on the right. For example:
go
x := 1 // Declaring and initializing variable x with value 1

In this example, we don't explicitly declare x as int; Go automatically infers x's type as int because we assign an integer 1 to x.

It's important to note that := can only be used inside functions, while = can be used anywhere to assign values to variables. Additionally, := cannot be used for already declared variables, otherwise it will cause a compilation error. However, when multiple variables are declared in the same scope and only one is new, := can be used. For example:

go
var a int a, b := 1, 2 // Here, `a` is a previously declared variable, while `b` is newly declared

In this example, a has already been declared, while b is a new variable, so := can be used.

In summary, = is used to assign values to existing variables, while := is used to declare new variables and assign values simultaneously.

2024年6月29日 12:07 回复

:= is a shorthand for declaration.

go
a := 10 b := "gopher"

a will be declared as an int and initialized with the value 10, while b will be declared as a string and initialized with the value gopher.

Its equivalent is =, which is used as follows:

go
var a = 10 var b = "gopher"

= is an assignment operator. It is used as an assignment operator in the same way as in other languages.

When declaring a variable with an initializer, you can omit the type (see http://tour.golang.org/#11).

2024年6月29日 12:07 回复

:= denotes declaration and assignment, while = denotes simple assignment.

2024年6月29日 12:07 回复

In Go, := is used for both declaration and assignment, while = is used solely for assignment.

For example, var foo int = 10 is equivalent to foo := 10.

2024年6月29日 12:07 回复

你的答案