Suppose I have this struct
type Rectangle struct {
height string
width string
}
And I have a test variable that exactly looks like this
testvar := []*Rectangle{
{
height: "100",
width: "100",
},
{
height: "200",
width: "200",
},
}
What I'm trying to do here is to append this test variable into another []*Rectangle with this looping
anothervar:= []*Rectangle{}
for _, ptr := range testvar {
fmt.Printf("%v\n", ptr)
anothervar = append(anothervar, ptr)
fmt.Printf("%p %v \n", anothervar, anothervar)
fmt.Println()
}
At the end, I got this output
What I wanted to print is anothervar address and value
CodePudding user response:
Not sure this is what you want. But following link of playground code allow you print the content of array of struct pointer by using non-built-in library.
https://go.dev/play/p/tcfJYb0NnVf
You may want to refer to the library to know how to print content or just use the library itself.
CodePudding user response:
The issue is that your slice is a slice of pointer to rectangle, so when it is printed out, it is printing out the values, but those values are pointers.
You could try something like this to print out the values:
import (
"fmt"
)
type Rectangle struct {
height string
width string
}
func main() {
testvar := []*Rectangle{
{
height: "100",
width: "100",
},
{
height: "200",
width: "200",
},
}
anothervar:= []*Rectangle{}
for _, ptr := range testvar {
fmt.Printf("%v\n", ptr)
anothervar = append(anothervar, ptr)
fmt.Printf("%p % v \n", anothervar, anothervar)
fmt.Println()
printRectSlice(anothervar)
}
}
func printRectSlice(s []*Rectangle) {
fmt.Printf("{")
for _, r := range s {
fmt.Printf("%v", *r)
}
fmt.Println("}")
}