How to create top level object without fields or methods in Golang?

Since I am from Java and new to Golang, I will try to explain what I want in Java.

    interface Car { }

    class MyCarA implements Car {
      int specificToA
    }

    class MyCarB implements Car {
      int specificToB
    }

      

I think an interface like this (like Car) is called a marker interface in Java. It's just to tell the compiler the abstraction it needs.

How can I do this in Golang?

I have

type MyCarA struct {
   specificToA int
}
type MyCarB struct {
  specificToB int
}

      

How can I generalize these structures now? Should it be an interface or some other structure?

-1


source to share


2 answers


You can do it:

type Car interface { IAmACar() }

type MyCarA struct {
  specificToA int
}
func (MyCarA) IAmACar() {}

type MyCarB struct {
  specificToB int
}
func (MyCarB) IAmACar() {}

      

You validate the token using the assertion type :

_, itIsACar := v.(Car)

      



playground example

The Car interface can also be used for statistical error detection:

var c Car
c = MyCarA{0} // ok
c = 0 // error, int is not a car

      

The go / ast package does something similar. See. Using exprNode file ast.go .

+5


source


The above method is correct and works for run-time detection, but it does not provide compile-time detection. If you want to determine compile time, pass the type of the function that takes an interface as an argument and check. See example below:

package main

import "fmt"

type MyType struct {
    a int
    b int
}

type NotMyType struct {
    a int
    b int
}

type Printer interface {
    Print(a string) error
}

func (m *MyType) Print(s string) error {
    fmt.Println(m.a, m.b, s)
    return nil
}

//Uncomment following function to see compilation work
// func (m *NotMyType) Print(s string) error {
//  fmt.Println(m.a, m.b, s)
//  return nil
// }

func main() {
    t := &MyType{
        a: 1, b: 2,
    }

    t1 := &NotMyType{
        a: 1, b: 2,
    }

    checkPrintable(t)
    checkPrintable(t1)
}

func checkPrintable(p Printer) {
    p.Print("Test message")
}

      



To do this, you need to uncomment the Print function for NotMyType.

Hope it helps.

0


source







All Articles