gpt4 book ai didi

go - 从接收器函数返回数组长度

转载 作者:行者123 更新时间:2023-12-01 22:41:15 25 4
gpt4 key购买 nike

我有一个数组为:

// Stock file
type Stock []StockLine
并希望获得此数组的长度为:
//Records returns number of records in the stock file
func (s *Stock) Records() int {
return len(*s)
}
但是返回的输出看起来是地址而不是长度,我得到了:
0x1154420
最低运行示例:
package main

import (
"fmt"
)

type Stock []StockLine

type StockLine struct {
Resource string
Color string
Style string
Size string
Quantity int64
}

func main() {
fmt.Println("Hello, playground")
stock := Stock{}
stock = append(stock, StockLine{
Resource :"Shirt",
Color :"Blue",
Style :"Modern",
Size :"XL",
Quantity :10,
})

fmt.Printf("%v", stock.Records)

}

//Records returns number of records in the stock file
func (s *Stock) Records() int {
return len(*s)
}
如何返回正确的长度?

最佳答案

fmt.Printf("%v", stock.Records)将打印函数的地址;如果您想要结果,则需要add brackets,即所谓的fmt.Printf("%v", stock.Records())

关于go - 从接收器函数返回数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63695675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com