gpt4 book ai didi

go - 无法通过 var.MethodName() 从另一个包访问方法

转载 作者:IT王子 更新时间:2023-10-29 02:09:18 27 4
gpt4 key购买 nike

我有一个包,其中包含一些与之相关的结构和函数:

package samplepkg

type SampleStruct struct {
FirstString string
SecondString string
}

func init() {
// some operations
}

func CheckSomething(s *SampleStruct) bool {
// check something
}

现在我试图在另一个包中运行这个函数:

import (
"MyProject/samplepkg"
)

func testFunc() {
var s = samplepkg.SampleStruct{"a", "b"}
if s.CheckSomething() {
// do some operations
}
}

但是我得到一个错误,说 s.CheckSomething 是未定义的。 (&s).CheckSomething 给出相同的结果。我可以访问 s.FirstString 和 s.SecondString 以及通过调用来使用此方法

if samplepkg.CheckSomething(&s) {
// do some operations
}

但我觉得它可以用更好的方式编写。我知道 Go 不是面向对象的语言,但是这样的方法调用可能吗?

最佳答案

在 Golang 中,方法集定义为:

A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.

有一个错误,因为你在调用函数时使用了指针接收器 with 方法。所以在定义方法时将函数更改为:

func init() {
// some operations
}

func(s *SampleStruct) CheckSomething() bool {
// check something
}

或者当调用方法时,它应该是带有参数 SampleStruct 的函数,就像

import (
"MyProject/samplepkg"
)

func testFunc() {
var s = &samplepkg.SampleStruct{"a", "b"}
if CheckSomething(s) {
// do some operations
}
}

关于go - 无法通过 var.MethodName() 从另一个包访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016699/

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