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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?