writing to a pointer but the compiler still complains unused variable - go

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

Related

How to change elements in a list?

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}

os.Read() How is work? Golang

Why if I print bs, before calling Read(), it prints nothing, but after the call file.Read(bs), it shows the inside of test.txt file. Unless bs is only argument, how Read() can Change it?
package main
import (
"os"
"fmt"
)
func main() {
file , err := os.Open("test.txt")
if err == nil {
} else {
}
stat , _ := file.Stat()
bs := make([]byte, stat.Size())
fmt.Println(string(bs))
bsf ,err := file.Read(bs)
if err != nil{
fmt.Println(err)
fmt.Println(bsf)
}
fmt.Println(string(bs))
}
Output:
(Line1)
(Line2)hi, This is Example text in test.txt file.
Unless bs is only argument, how Read() can Change it?
It seems that you may be missing basic knowledge about programming languages in general. There are different kind of "values". There are pointers (or references) and there are the "usual values".
For example:
package main
import (
"fmt"
)
func changeIt(p *int) {
*p = 9
}
func main() {
a := 1
fmt.Println(a)
changeIt(&a)
fmt.Println(a)
}
It'll print 1 9 not 1 1. *int is not an integer, but a pointer to an integer. A pointer is a value that points (references) another value. If you have a value of type pointer you get the actual value that the pointer points to by using * (which is called dereferencing):
func main() {
a := 1
b := &a
fmt.Println(b, *b)
}
b is a pointer (of type *int) that points to a. The println will print the location of a followed by the value of a which is usually something like uhm 0x10414020 1. We can also modify the value a pointer points to by using *p = ...:
func main() {
a := 1
b := &a
*b = 9
fmt.Println(b, *b, a)
}
which will print 0x10414020 9 9.
Now, []byte is a slice... slices are like pointers. When you do
func changeIt(buf []byte) {
buf[0] = 10
}
func main() {
data := []byte{1,2,3}
changeIt(data)
fmt.Println(data)
}
You're not actually passing the values [1 2 3] to changeIt but a pointer to those values. Thus here the println will show [10 2 3]. Compare this to:
func changeIt(buf [3]byte) {
buf[0] = 10
}
func main() {
data := [3]byte{1,2,3}
changeIt(data)
fmt.Println(data)
}
Which will print [1 2 3] and it will pass the values [1 2 3] and not a pointer so changeIt essentially works on a copy and the buf[0] = 10 has no effect. Remember: [n]T is an array, []T is a slice. [n]T is a "raw value" and []T is a "pointer value".

some confusions about lambda function/closure in Golang

package main
import (
"fmt"
)
func main(){
f,val,val1:=fibonacci()
fmt.Println(val,val1)
for i:=0;i<=10;i++ {
fmt.Println(f(i),val,val1)
}
_,val,val1=fibonacci()
fmt.Println(val,val1)
}
func fibonacci()(func(n int)int,int,int){
var val int
var val1 int
f:=func(n int)int{
if n==0||n==1{
val,val1=1,1
}else{
val,val1=val+val1,val
}
return val
}
fmt.Println("fibonacci val =",val,"val1 =",val1)
return f,val,val1
}
Here is my code on sloving fibonacci without using recursion when I
read about lambda function/closure. And the Go Documentary says a
closure will capture some external state. My understanding is the
closure will keep a copy of state of the function which it is
declared. These states are just copies whatever I do on them won't
modify the original, is that so?
from your test code here: https://play.golang.org/p/pajT2bAIe2
your fibonacci function is working out the nth numbers in the sequence provided it's called in an incremental fashion as you are doing. but the values you return from the initial call to fibonacci are not pointers (or references) to those integer values they are just the values of those integers at that time, think of them as being copied out of the function, try using integer pointers instead like this: https://play.golang.org/p/-vLja7Fpsq
package main
import (
"fmt"
)
func main() {
f, val, val1 := fibonacci()
fmt.Println(val, val1)
for i := 0; i <= 10; i++ {
fmt.Println(f(i), *val, *val1) //dereference the pointer to get its value at the current time
}
_, val, val1 = fibonacci()
fmt.Println(*val, *val1)
}
func fibonacci() (func(n int) int, *int, *int) {
var val int
var val1 int
f := func(n int) int {
if n == 0 || n == 1 {
val, val1 = 1, 1
} else {
val, val1 = val+val1, val
}
return val
}
fmt.Println("fibonacci val =", val, "val1 =", val1)
return f, &val, &val1 // return pointers to the closured values instead of just the values
}
Although you have accepted the above answer i'm giving another explanation. The reason why you receive the last value of the loop operation has to do with the Go's lexical scoping. The for loop introduces a new lexical block in which the value is referenced by it's memory address, so by pointer and not by it's value. In order to get the value, you have to de-reference.
Each time the for loop makes an iteration the value processed is pointing to the same memory address. All the function values created by this loop "capture" and share the same variable - and addressable storage location, not it's value at that particular moment. Thus when the last iteration is finished, the variable holds the value from the final step.
A much better approach for these kind of operations would be to use goroutines, because in these cases you are not communicating through sharing the same memory address, but you are sharing the memory through communication.
Here is a more elegant solution using goroutine:
package main
import (
"fmt"
)
func fibonacci(ch chan interface{}, quit chan struct{}) {
x, y := 1, 1
for {
select {
case ch <- x:
x, y = y, x+y
fmt.Println(x , y)
case <-quit:
fmt.Println("Quiting...")
return
}
}
}
func main() {
ch := make(chan interface{})
quit := make(chan struct{})
go func() {
for i := 0; i < 10; i++ {
<-ch
}
quit <- struct{}{}
}()
fibonacci(ch, quit)
}
https://play.golang.org/p/oPQgXWyV9u

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.

Different behavior between calling function directly and using pointer

I am new to Go language and got confused with the following code
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
previous := 0
current := 1
return func () int{
current = current+previous
previous = current-previous
return current
}
}
func main() {
f := fibonacci
for i := 0; i < 10; i++ {
fmt.Println(f()())
}
}
This code is supposed to print out the Fibonacci Sequence (first 10), but only print out 10 times 1.
but if I change the code to:
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Then it is working fine. The output is the Fibonacci sequence.
Could any one help me explain this?
Thanks
fibonacci() creates a new fibonacci generator function. fibonacci()() does the same, and then calls it once, returns the result and discards the generator, never to be used again. If you call that in a loop, it'll just keep creating new generators and only using their first value.
If you want more than just the first value, you need to do exactly what you did in your second example. Store the generator itself in a variable and then call the same generator multiple times.
This has to do with how variables are encapsulated in closures after returning the closure.
Consider the following example (live code on play):
func newClosure() func() {
i := 0
fmt.Println("newClosure with &i=", &i)
return func() {
fmt.Println(i, &i)
i++
}
}
func main() {
a := newClosure()
a()
a()
a()
b := newClosure()
b()
a()
}
Running this code will yield something like the following output. I annotated
which line comes from which statement:
newClosure with &i= 0xc010000000 // a := newClosure()
0 0xc010000000 // a()
1 0xc010000000 // a()
2 0xc010000000 // a()
newClosure with &i= 0xc010000008 // b := newClosure()
0 0xc010000008 // b()
3 0xc010000000 // a()
In the example, the closure returned by newClosure encapsulates the local variable i.
This corresponds to current and the like in your code. You can see that a and b
have different instances of i, or else the call b() would've printed 3 instead.
You can also see that the i variables have different addresses. (The variable is already
on the heap as go does not have a separate stack memory, so using it in the closure is
no problem at all.)
So, by generating a new closure you're automatically creating a new context for the
closure and the local variables are not shared between the closures. This is the reason
why creating a new closure in the loop does not get you further.
The equivalent in for your code in terms of this example would be:
for i:=0; i < 10; i++ {
newClosure()()
}
And you've already seen by the output that this will not work.
func fibonacci() func() int return a function literal (closure) that returns an int representing the last generated number in the list.
The first main() method
f := fibonacci
for i := 0; i < 10; i++ {
fmt.Println(f()())
}
f is the generator function, every iteration in the loop invoke f()() that generates a new closure with a new envirement ( previous := 0, current := 1), so , the second invocation returns current which is always equal to 1.
The second main() method
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
f is the closure (not the generator) with an initial envirement ( previous := 0, current := 1), every iteration in the loop invoke f() witch returns current and modify the envirement, so whith the next call, previous will be 1 and current 2.

Resources