I am trying to create a list of structures and assign values to components of each structure in the list:
package main
import ("fmt";"strconv")
type Mystruct struct{
code string
val int
}
var stlist []Mystruct // Need to create this list
func main(){
//Trying to create list of structures and assigning values:
for i,_:=range [3]int{} {
var st =Mystruct{}
stlist = append(stlist, st)
st.val = i
st.code = "code_"+strconv.Itoa(i)
fmt.Println("st.code=", st.code, "; st.val=", st.val) // Looks OK.
}
//check values of each item of list:
fmt.Println( "-----------------------" )
for _,e := range stlist{
fmt.Println("st.code=", e.code, "; st.val=", e.val) // values are blank! Why?
}
}
Above code compiles and runs without any error. However, as mentioned in comments above, although the values seem to be assigned to each component of the list, in second loop, it is found that both components of all structs in the the struct list are blank. The output is:
st.code= code_0 ; st.val= 0
st.code= code_1 ; st.val= 1
st.code= code_2 ; st.val= 2
-----------------------
st.code= ; st.val= 0
st.code= ; st.val= 0
st.code= ; st.val= 0
Where is the problem and how can it be solved? Thanks for your help.