Reputation: 146
Actually i just start to learn golang . In the beginning i think that =
and :=
are same . But then i understand that there is some difference between this two .
I learned swap function in golnag
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
But when i rewrite this function using var
this is not working
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
var a, b string
a ="hello"
b="world"
swap(a, b)
fmt.Println(a, b)
}
what is the error in this program ?
Upvotes: 0
Views: 3789
Reputation: 31139
var a string
- declaration of a variable with null value a := "spam"
- declaration of a variable with a concrete valuefunc f(a, b string) (string, string) {
- declaration of a function with value parameters. It means you have new variables with passed values as arguments each time you call a function.func f(a, b *string) (*string, *string) {
- declaration of a function with pointer arguments. In it's turn it means you have pointers to passed variables each time you call the function.Also...
a := *string
- declaration of a pointer variable.*a
- value of a pointer variable.&a
- pointer of a valueTo swap in-place (without returning and reassigning) you should swap values between pointers.
func swap(a, b *string) {
*a, *b = *b, *a
}
p.s.
Take into account that strings is read-only slices of bytes. And slices are reference type it means that an array behind the sub-slices of a common array or slice is the same. It doesn't related to the question but should be considered in such cases.
Upvotes: 2
Reputation: 3071
Another solution is to use pointers:
package main
import "fmt"
func swap(x, y *string) {
*x, *y = *y, *x
}
func main() {
var a, b string
a ="hello"
b="world"
swap(&a, &b)
fmt.Println(a, b)
}
https://play.golang.org/p/-vxUMlaVmN
Upvotes: 8
Reputation: 4770
To respond your initial question, you should assign the values returned by swap to a and b like so
a, b = swap(b, a)
Notice that this is simple assignment , without the :
attached to the equal
also, instead of a swap
function, you could just try inplace reassignment:
a, b = b, a
Upvotes: 3
Reputation: 12845
The reason is that in second case values returned from swap
are ignored. SO nothing is changed.
Try: https://play.golang.org/p/uADEf5X15g
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
var a, b string
a = "hello"
b = "world"
a, b = swap(a, b) //// <----
fmt.Println(a, b)
}
Upvotes: 2