[英]Append slice of pointer into another slice of pointer Go
假設我有這個結構
type Rectangle struct {
height string
width string
}
我有一個完全像這樣的測試變量
testvar := []*Rectangle{
{
height: "100",
width: "100",
},
{
height: "200",
width: "200",
},
}
我在這里要做的是將這個測試變量 append 變成另一個 []*Rectangle 循環
anothervar:= []*Rectangle{}
for _, ptr := range testvar {
fmt.Printf("%v\n", ptr)
anothervar = append(anothervar, ptr)
fmt.Printf("%p %v \n", anothervar, anothervar)
fmt.Println()
}
最后,我得到了這個output
我想打印的是 anothervar 地址和值
不確定這是你想要的。 但是下面的游樂場代碼鏈接允許您使用非內置庫打印結構指針數組的內容。
https://go.dev/play/p/tcfJYb0NnVf
您可能想參考圖書館以了解如何打印內容或只使用圖書館本身。
問題是你的切片是指向矩形的指針切片,所以當它被打印出來時,它正在打印出值,但這些值是指針。
你可以嘗試這樣的事情來打印出這些值:
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("}")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.