dtcuv8044 2016-03-14 04:22
浏览 60

在golang中,您如何访问采用指针接收器并且也位于其他程序包中的方法?

package tests

import (
    "testing"
    "strconv"
    "dir/model"
)

type TestStruct struct {
    ID int
    a  string
    b  string
    c  string
    d  string
    ac bool
    ad bool
}

func TestUpdate(t *testing.T) {

        t.Log("Updating")
        cur := TestStruct{i,a,b,c,d,true,true}
        err := cur.model.Update(a,b,c,d,true,true)
}

In the code block above, I am trying to call a method that takes a receiver pointer and that is located in package "model".

The compiler error for this is:

reference to undefined field or method ‘model’ err := cur.model.Update(a,b,c,d,e,true,true)

In the code block below,the method "Udpate" in package "model" takes a receiver point to a struct and other input parameters.

package model

type Struct struct {
    ID int
    a  string
    b  string
    c  string
    d  string
    ac bool
    ad bool
}

func (update *Struct) Update(a, b, c, d,
e string, f, g bool) error {

    /* code */

}

I know for functions in other packages I can call them in my current package by saying:

packageName.method(parameters) 

How could I call method "Update" from package "model" in package "tests" while inputting a receiver pointer when I call it?

  • 写回答

2条回答 默认 最新

  • doucang6914 2016-03-14 04:26
    关注
    func (update *Struct) Update(a, b, c, d, e string, f, g bool)
    

    is a method that is defined on type model.Struct. You cannot call it on a different type, such as TestStruct defined in your tests package.

    What you probably want to do is:

        cur := model.Struct{i,a,b,c,d,true,true}
        err := cur.Update(a,b,c,d,true,true)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题