Golang中如何从接收器函数返回数组长度

Golang中如何从接收器函数返回数组长度 我有一个数组如下:

// 股票文件
type Stock []StockLine

并且想要获取这个数组的长度,如下所示:

// Records 返回股票文件中的记录数量
func (s *Stock) Records() int {
	return len(*s)
}

但返回的输出看起来是地址而不是长度,我得到了:

0x1154420

我该如何返回正确的长度?

2 回复

hyousef: 如何返回正确的长度?

你的代码看起来是有效的。

package main

import "fmt"

type StockLine struct{}

// Stock file
type Stock []StockLine

//Records returns number of records in the stock file
func (s *Stock) Records() int {
	return len(*s)
}

func main() {
	stock := Stock(make([]StockLine, 7))
	fmt.Println(stock.Records())
}

Go Playground - The Go Programming Language

$ go run stock.go
7
$

请提供一个能复现你结果的简单示例。

更多关于Golang中如何从接收器函数返回数组长度的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你遇到的问题是因为在调用 Records 方法时,没有正确调用它。0x1154420 是一个地址值,这意味着你打印的是方法本身而不是调用它的结果。以下是正确的做法:

package main

import "fmt"

type StockLine struct {
    // 假设有一些字段
}

type Stock []StockLine

// Records 返回股票文件中的记录数量
func (s *Stock) Records() int {
    return len(*s)
}

func main() {
    // 示例数据
    stock := Stock{
        StockLine{},
        StockLine{},
        StockLine{},
    }

    // 正确调用方法
    length := stock.Records()
    fmt.Println(length) // 输出: 3

    // 或者使用指针
    stockPtr := &stock
    length2 := stockPtr.Records()
    fmt.Println(length2) // 输出: 3

    // 错误示例:打印方法值而不是调用结果
    fmt.Println(stock.Records) // 这会输出地址: 0x...
}

你的 Records 方法实现是正确的。问题在于调用方式。确保你使用了括号 () 来调用方法:

// 正确
count := stock.Records()

// 错误 - 这会得到方法值(地址)
methodValue := stock.Records

如果你在模板或其他地方使用这个方法,确保调用语法正确:

// 在模板中正确调用
{{ .Stock.Records }}

// 如果是在Go代码中打印
fmt.Println(stock.Records())

方法本身没有问题,问题在于调用时缺少了括号 (),导致获取到的是方法值而不是调用结果。

回到顶部