2

How can you implement virtual functions in golang? I tried this, but i can't make it print "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

user3526468
  • 334
  • 5
  • 14
  • 2
    Also, if you write a program in Golang, write go code. – T. Claverie Jun 05 '16 at 12:54
  • This is actually not a duplicate question in my view. Here is my answer (and yes, I think the Golang standard of _not_ using "this" is stupid) https://play.golang.org/p/k4K0SUvgGol – Daniel Santos Jun 03 '21 at 17:46

1 Answers1

0

use Golang interface methods instead of C++ (pure) virtual functions:
for the The Go Way to this see package sort:

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)
}

and sample (custom sorting with age):

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}]
}