doubo6658 2018-08-25 11:08
浏览 17
已采纳

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

I have a package containing some structure and functions associated with it:

package samplepkg

type SampleStruct struct {
    FirstString string
    SecondString string
}

func init() {
    // some operations
}

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

Now I'm trying to run this function in another package:

import (
    "MyProject/samplepkg"
)

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

But I get an error that s.CheckSomething is undefined. (&s).CheckSomething gives the same result. I can access s.FirstString and s.SecondString as well as use this method by calling

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

But I feel it could be written in a better way. I'm aware that Go is not object-oriented language but is method invocation like this possible?

  • 写回答

1条回答 默认 最新

  • duanfan1869 2018-08-25 11:18
    关注

    In Golang a Method set is defined as:

    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.

    There is a mistake because you are using the pointer receiver with method when calling the function. So change the function when defining to method as:

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

    Or when calling the method it should be function with argument SampleStruct which will be like

    import (
        "MyProject/samplepkg"
    )
    
    func testFunc() {
        var s = &samplepkg.SampleStruct{"a", "b"}
        if CheckSomething(s) {
            // do some operations
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法