小编use*_*400的帖子

golang在T和*T上区分方法集的原因是什么?

这是学习的最让我困惑的地方.我们都知道方法T只影响副本T,而方法*T会影响实际数据T.

为什么方法T也可以使用*T,但不允许相反?所以,你可以给我为什么他们不允许对方法的示例(或原因)*T被使用T

这个设计的优点和缺点是什么?

methods go

6
推荐指数
2
解决办法
1223
查看次数

如何在golang中正确打印指针变量

type person struct{}
var tom *person = &person{}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我用的时候

fmt.Printf("%+v\n", tom)//prints:&{}
Run Code Online (Sandbox Code Playgroud)

为什么结果是&加数据?它被认为是一个地址(0x0055)

我用的时候

fmt.Printf("%+v\n", &tom)//0x0038
fmt.Printf("%p\n", &tom)//0x0038
Run Code Online (Sandbox Code Playgroud)

它给了我一个地址,它给了我0x0038,为什么%v和%p有相同的结果?

pointers go

6
推荐指数
1
解决办法
6504
查看次数

在Go中将函数转换为另一种类型(函数转换)

我最近了解到,在net/http包装中,有一种使用模式让我最困惑.它是功能类型转换.它是这样的:

(function a) ->convert to-> (type t)
(type t) ->implentments-> (interface i)
Run Code Online (Sandbox Code Playgroud)

因此,如果有一个以接口i作为参数的函数,它将调用函数a,这是net/http实现它的方式.

但是当我编写自己的代码时,我对这种模式有很多误解.我的代码是这样的:

package main

import (
    "fmt"
)

type eat interface {
    eat()
}
type aaa func()

func (op *aaa) eat() {//pointer receiver not right
    fmt.Println("dog eat feels good")
}

///////////////////////////////////////////////
func dog() {
    fmt.Println("I'm a dog")
}
///////////////////////////////////////////////

func feelsGood(a eat) {
    a.eat()
}

func main() {
    b := aaa(dog)
    feelsGood(b)
}

//error:aaa does not implement eat (eat method has pointer …
Run Code Online (Sandbox Code Playgroud)

types function type-conversion go

4
推荐指数
1
解决办法
6705
查看次数

标签 统计

go ×3

function ×1

methods ×1

pointers ×1

type-conversion ×1

types ×1