gpt4 book ai didi

go - 为什么不能同时为结构及其指针定义方法?

转载 作者:IT王子 更新时间:2023-10-29 01:11:15 25 4
gpt4 key购买 nike

鉴于 54th slide 中的设置golang 之旅:

type Abser interface {
Abs() float64
}

type Vertex struct {
X, Y float64
}

func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

为什么不能同时为结构体和指向结构体的指针定义方法?即:

func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

定义它会产生以下错误:

prog.go:41: method redeclared: Vertex.Abs
method(*Vertex) func() float64
method(Vertex) func() float64

最佳答案

可以。只需在结构而不是指针上定义它。它将解决两种方式

Method Sets

The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T)

在线试听:http://play.golang.org/p/PsNUerVyqp

package main

import (
"fmt"
"math"
)

type Abser interface {
Abs() float64
}

type Vertex struct {
X, Y float64
}

func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
v := Vertex{5, 10}
v_ptr := &v
fmt.Println(v.Abs())
fmt.Println(v_ptr.Abs())
}

更新: 根据评论,我创建了一个额外的示例,该示例实际使用 Abser 接口(interface)来说明值和指针都满足该接口(interface)。

https://play.golang.org/p/Mls0d7_l4_t

关于go - 为什么不能同时为结构及其指针定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com