【问题标题】:How to implement virtual functions in golang? [duplicate]golang如何实现虚函数? [复制]
【发布时间】:2016-06-05 11:53:18
【问题描述】:

如何在 golang 中实现虚函数?我试过这个,但我不能让它打印“B”

type A struct {
}

type B struct {
  A
}

func (self A) myVirtualFunction() {
    fmt.Println("A again :(")
}

func (self A) f() {
    self.myVirtualFunction()
}

func (self B) myVirtualFunction(){
    fmt.Println("B :)")
}

func main() {
    var b *B = new(B)
    b.f()
}

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

【问题讨论】:

  • 另外,如果你用 Golang 编写程序,请编写 go 代码。
  • 在我看来,这实际上不是一个重复的问题。这是我的答案(是的,我认为 not 使用“this”的 Golang 标准是愚蠢的)play.golang.org/p/k4K0SUvgGol

标签: go


【解决方案1】:

使用 Golang 接口方法而不是 C++(纯)虚函数:
对于 Go Way to this,请参阅包排序:

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

和样本(按年龄自定义排序):

package main

import "fmt"
import "sort"

type Person struct {
    name string
    age  int
}
type PS []Person

// Len is part of sort.Interface.
func (s PS) Len() int {
    return len(s)
}

// Swap is part of sort.Interface.
func (s PS) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

// Less is part of sort.Interface.
func (s PS) Less(i, j int) bool {
    return s[i].age < s[j].age
}

func main() {
    s := PS{Person{"Alex", 23}, Person{"Jane", 22}}
    fmt.Println(s) // [{Alex 23} {Jane 22}]
    sort.Sort(s)
    fmt.Println(s) // [{Jane 22} {Alex 23}]
}

【讨论】:

    猜你喜欢
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2010-09-11
    • 2015-11-30
    • 2021-07-21
    • 2010-12-13
    相关资源
    最近更新 更多