In Go, both the =
and <-
operators are used for assignment, but they serve different purposes and are used in different contexts. Here’s a breakdown of the key differences between them:
1. =
(Regular Assignment Operator):
- Purpose: The
=
operator is used for regular assignment in Go. It assigns a value to a variable, and it’s used within functions, including when modifying the value of existing variables. - Usage: It can be used for initializing variables and reassigning values to already declared variables.
Example:
package main
import "fmt"
func main() {
var x int = 10 // Regular assignment with declaration
x = 20 // Reassigning the value of x
fmt.Println(x) // Output: 20
}
In this example:
- The
=
operator assigns a value tox
(both when initializing it and later when reassigning its value).
2. <-
(Channel Assignment Operator):
- Purpose: The
<-
operator is used for sending or receiving values on Go channels. It is not used for regular variable assignment like=
.- Sending values: You use
<-
to send a value into a channel. - Receiving values: You use
<-
to receive a value from a channel.
- Sending values: You use
Example (Sending and Receiving):
package main
import "fmt"
func main() {
ch := make(chan int) // Create a channel of type int
go func() {
ch <- 42 // Send the value 42 into the channel
}()
value := <-ch // Receive the value from the channel
fmt.Println(value) // Output: 42
}
In this example:
ch <- 42
sends the value42
into the channelch
.value := <-ch
receives the value from the channelch
and assigns it tovalue
.
Key Differences:
Operator | Purpose | Usage Context | Example |
---|---|---|---|
= |
Regular assignment (used for variables) | Used to assign values to variables | x = 10 |
<- |
Channel operations (sending or receiving data) | Used for sending/receiving data to/from channels | ch <- 10 (send), x := <-ch (receive) |
Additional Notes:
=
: Works with regular variables. You use it to assign values to already declared variables or to declare and assign values simultaneously in some cases.<-
: Specifically for channels, and it’s used for communication between goroutines. You cannot use<-
for regular variable assignment.
Example with both in a program:
package main
import "fmt"
func main() {
var a int = 10 // Regular assignment using `=`
ch := make(chan int) // Channel assignment
go func() {
ch <- 42 // Sending value to the channel
}()
a = <-ch // Receiving value from the channel and assigning it to `a`
fmt.Println(a) // Output: 42
}
In this case:
a = 10
uses the=
operator for regular variable assignment.ch <- 42
anda = <-ch
use the<-
operator for sending and receiving values to/from a channel.