This question is not as clear as I wanted to be I will ask a better question. But I do not want to marked duplicate on that. So I have flagged my own question. If you can help it to be deleted to not confuse the community. Please do the needful. Please do not downvote me while you are at it. Sorry to be unclear

我是golang的新手,只是掌握了它 .

我正在学习Tour of Go,然后以我自己的理解使用它 . 我在Interfaces并开始以我自己的理解实施 . 这是Go PlayGround Link

第1步:我将3种类型设为int,struct和interface

package main

import (
    "fmt"
)

type MyInt int

type Pair struct {
    n1, n2 int
}

type twoTimeable interface {
    result() (int, int)
}

第2步:然后我为指针接收器实现了twoTimeable,因为它改变了底层值 .

func (p *Pair) result() (int, int) {
    p.n1 = 2 * p.n1
    p.n2 = 2 * p.n2
    return p.n1, p.n2
}

func (m *MyInt) result() (int, int) {
    *m = 2 * (*m)
    return int(*m), 0
}

第3步:然后我在main函数中声明并分配了MyInt,Pair及其相应的指针 . 我还声明了twoTimeable接口

mtemp := MyInt(2)
var m1 MyInt
var m2 *MyInt
var p1 Pair
var p2 *Pair
m1, m2, p1, p2 = MyInt(1), &mtemp, Pair{3, 4}, &Pair{5, 6}
var tt twoTimeable

fmt.Println(" Values  : ", m1, *m2, p1, *p2, tt)

第4步:我分配了MyInt,Pair和它们的指针,称为已实现的方法并打印出来 .

tt = m1
fmt.Println(tt.result())
fmt.Printf("Value of m1 %v\n", m1)

tt = m2
fmt.Println(tt.result())
fmt.Printf("Value of m2 %v\n", *m2)

tt = p1
fmt.Println(tt.result())
fmt.Printf("Value of p1 %v\n", p1)

tt = p2
fmt.Println(tt.result())
fmt.Printf("Value of p2 %v\n", *p2)

它显示错误:

prog.go:41:5: cannot use m1 (type MyInt) as type twoTimeable in assignment:
    MyInt does not implement twoTimeable (result method has pointer receiver)
prog.go:49:5: cannot use p1 (type Pair) as type twoTimeable in assignment:
    Pair does not implement twoTimeable (result method has pointer receiver)
p1/m1.result()

*Now in Step 2 when I change the pointer receiver to value receiver, and change m to m(I am aware of change in Output)

func (p Pair) result() (int, int) {
    p.n1 = 2 * p.n1
    p.n2 = 2 * p.n2
    return p.n1, p.n2
}

func (m MyInt) result() (int, int) {
    m = 2 * (m)
    return int(m), 0
}

它突然没有显示编译错误 . 不应该为m2和p2,因为现在没有使用* MyInt和* Pair的结果实现

这意味着如果接口方法实现具有值接收器tt可以保持指针和值 . 但是当接口方法实现有指针接收器时,它不能保持非指针 .

Q1:为什么在值接收器接口方法(p MyInt)result()上使用指针(tt = m2),而不是在指针接收器接口方法(p * MyInt)result()上使用值(tt = m1) .

现在让我们回到指针接收器 .

有没有一种方法,如果函数接受参数(tt twoTimeable)我将能够调用tt.result()而不管是否是指向类型的指针,给定result()仅用指针接收器定义 .

请参阅以下代码:

func doSomething(tt twoTimeable) {
    temp1, temp2 := tt.result()
    fmt.Print("doing something with ", temp1, temp2)
}

因为tt可以是任何预定义的类型(指针或不是指针),所以运行param(tt * twoTimeable,如果我甚至可以这样做)似乎不是解决方案,或者我依赖于函数用户来提供指针 . 如果我不必更改基础值,即使用值接收器它不是一个问题,因为tt可以保持值或指针

我总是接受回答 .