How to change elements in a list? - go

If I use container/list as
package main
import (
"container/list"
"fmt"
)
type Data struct {
x int
}
func main() {
l := list.New()
l.PushBack(Data{2})
a := l.Back()
v := a.Value.(Data)
v.x = 1
fmt.Println(l.Back().Value) // --> {2}
}
Well, the value of x in the list does not change. What is the correct programming pattern?

Function arguments and return values are passed by value in Go. Therefore v is a copy of the original Data value. Changing it does not affect the one that is stored in the list.
You can get the behaviour you want by inserting a pointer to a Data value instead:
l := list.New()
l.PushBack(&Data{2})
a := l.Back()
v := a.Value.(*Data)
v.x = 1
fmt.Println(l.Back().Value) // --> &{1}

Related

What does the underscore(_) do in for loop Golang?

I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.
Whatever add _ or not, I got the same result.
package main
import (
"fmt"
)
func main() {
doSomething()
sum := addValues(5, 8)
fmt.Println("The sum is", sum)
multiSum, multiCount := addAllValues(4, 7, 9)
fmt.Println("multisum", multiSum)
fmt.Println("multiCount", multiCount)
}
func doSomething() {
fmt.Println("Doing Something")
}
func addValues(value1 int, value2 int) int {
return value1 + value2
}
func addAllValues(values ...int) (int, int) {
total := 0
for _, v := range values {
total += v
}
return total, len(values)
}
func addAllValues(values ...int) (int, int) {
total := 0
for v := range values {
total += v
}
return total, len(values)
}
All I know is I don't care about the index. Is that all? or there is something more what I have to know??
I really appreciate your help!
For range over slices:
In for v := range values { the v is the index of the element in the slice.
In for _, v := range values { the v is the actual element value.
In for i, v := range values { the i is the index and the v is the element.
In for i, _ := range values { the i is the index of the element in the slice.
You can run this playground example to see the differences.
Range expression 1st value 2nd value
array or slice a [n]E, *[n]E, or []E index i int a[i] E
string s string type index i int see below rune
map m map[K]V key k K m[k] V
channel c chan E, <-chan E element e E
For more details see the spec.
If you don't want to use the variable that iterates in the loop, you can use _ to simply let Go ignore it:
mySlice := [int]{1,3,4,59,5}
for _,x := range mySlice {
fmt.Println(x)
}
By placing underscore you are telling the compiler this:
Ok, I'm aware that this function is returning something but I don't care! For example:
package main
import "fmt"
func main() {
mul1, add1 := test_function(2, 3)
fmt.Println(mul1, add1)
mul2, _ := test_function(4, 5)
fmt.Println(mul2)
_, add3 := test_function(7, 8)
fmt.Println(add3)
}
func test_function(a int, b int) (mul int, add int) {
return a * b, a + b
}
just to add to the amazing answer above:
I think one of the main benefits is to maintain readability in your program: if you replace the blank identifier with a variable then you have to use it or your program will not compile.
also this decrease memory allocation be neglecting one of the returned parameters...

writing to a pointer but the compiler still complains unused variable

The following code causes a compilation error:
main.go:8:9: p declared and not used
package main
func main() {
pointers := make([]*int, 5)
a := 1 // create an int
for _, p := range pointers {
p = &a
}
}
Writing to p doesn't count as using it?
P is only scoped to the loop block and essentially gets a copy of a pointers slice element every time it goes through the loop. This would work though:
package main
import "fmt"
func main() {
pointers := make([]*int, 5)
a := 1 // create an int
for i := range pointers {
pointers[i] = &a
}
fmt.Println(pointers)
}
Playground

create two dimensional string array in golang

I need to create a 2 dimensional string array as shown below -
matrix = [['cat,'cat','cat'],['dog','dog']]
Code:-
package main
import (
"fmt"
)
func main() {
{ // using append
var matrix [][]string
matrix[0] = append(matrix[0],'cat')
fmt.Println(matrix)
}
}
Error:-
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox863026592/main.go:11 +0x20
You have a slice of slices, and the outer slice is nil until it's initialized:
matrix := make([][]string, 1)
matrix[0] = append(matrix[0],'cat')
fmt.Println(matrix)
Or:
var matrix [][]string
matrix = append(matrix, []string{"cat"})
fmt.Println(matrix)
Or:
var matrix [][]string
var row []string
row = append(row, "cat")
matrix = append(matrix, row)
The problem with doing two-dimensional arrays with Go is that you have to initialise each part individually, e.g., if you have a [][]bool, you gotta allocate []([]bool) first, and then allocate the individual []bool afterwards; this is the same logic regardless of whether you're using make() or append() to perform the allocations.
In your example, the matrix[0] doesn't exist yet after a mere var matrix [][]string, hence you're getting the index out of range error.
For example, the code below would create another slice based on the size of an existing slice of a different type:
func solve(board [][]rune, …) {
x := len(board)
y := len(board[0])
visited := make([][]bool, x)
for i := range visited {
visited[i] = make([]bool, y)
}
…
If you simply want to initialise the slice based on a static array you have, you can do it directly like this, without even having to use append() or make():
package main
import (
"fmt"
)
func main() {
matrix := [][]string{{"cat", "cat", "cat"}, {"dog", "dog"}}
fmt.Println(matrix)
}
https://play.golang.org/p/iWgts-m7c4u

How to fill a slice with scan values

I'm brand new to Go and having trouble getting fmt.scan() to fill a slice. The number of input values is dynamic and I can't use a for loop. My initial thought was to try this:
package main
import "fmt"
func main() {
var x []int
fmt.Println("Enter input")
fmt.Scanf("%v", append(x))
fmt.Println(x)
}
Which obviously doesn't work. Can someone point me in the right direction?
[Get] fmt.Scan() to fill a slice. The number of input values is dynamic and I can't use a for loop.
Perhaps, something like this:
package main
import "fmt"
func input(x []int, err error) []int {
if err != nil {
return x
}
var d int
n, err := fmt.Scanf("%d", &d)
if n == 1 {
x = append(x, d)
}
return input(x, err)
}
func main() {
fmt.Println("Enter input:")
x := input([]int{}, nil)
fmt.Println("Input:", x)
}
Output:
Enter input:
1
2 3
4
5 6 7
Input: [1 2 3 4 5 6 7]
ADDENDUM:
When storage is allocated for a variable or a new value is created, and no explicit initialization is provided, the variable or value is given a default value, the zero value for its type: nil for slices. Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T. []int(nil) is a conversion to the zero value for the slice value []int.
x := input([]int(nil), nil)
is equivalent to
x := input([]int{}, nil)
or
var x []int
x = input(x, nil)
I have revised my answer to use:
x := input([]int{}, nil)
I'm new to Go, so this are my 2cents as a newbie.
func main(){
var numsToInput int
fmt.Println("Welcome user!")
fmt.Println("How many numbers would you like to scale today?")
fmt.Scan(&numsToInput)
fmt.Println("Type please the ", num, " numbers: ")
var values []float32 // Empty slice
for i := 0; i < num; i++{
var val float32
fmt.Scanln(&val)
values = append(values, val)
}
fmt.Println(values)
}
It's not a very elaborate program, but certainly it's simple.
I hope it was useful.
Using simple packages and more logic, you could try this,
package main
import "fmt"
func main() {
var ele rune
var size int
var sli = make([]int,0,1)
size = cap(sli)
for i:=0; i<=size; i++{
if i>=len(sli){
size=size+1
}
ele = 0
fmt.Println("Enter a number to add: ")
fmt.Scan(&ele)
if ele==0 {
fmt.Println("Stopping!")
break
}
sli = append(sli, int(ele))
}
fmt.Println(sli)
}
The code would stop and print the slice when you enter anything other than an integer.

How to fix 'declared but not used' compiler error in this simple program?

I am trying to learn Go. I really don't understand why the compiler is saying that I am not using a variable. It seems to me that I am using the variable as an argument to Println.
My textbook states:
In this for loop i represents the current position in the array and
value is the same as x[i]
package main
import "fmt"
func main() {
x := [5]float64{ 1,2,3,4,5 }
i := 0
var total float64 = 0
for i, value := range x {
total += value
fmt.Println(i, value)
}
fmt.Println("Average:", total / float64(len(x)))
}
Output on OS X:
go run main.go
# command-line-arguments
./main.go:8: i declared and not used
Surely this fmt.Println(i, value) is using the variable i?
How to fix the compiler message?
Remove the outer i from your program:
package main
import "fmt"
func main() {
x := [5]float64{1, 2, 3, 4, 5}
var total float64 = 0
for i, value := range x {
total += value
fmt.Println(i, value)
}
fmt.Println("Average:", total/float64(len(x)))
}
Surely this fmt.Println(i, value) is using the variable i?
Yes, but the one you're defining inside the for loop. (note the :=), here:
for i, value := range x
^ ^
The outer variable i is never used.

Resources