How can I use my Interface method?

Hello,

first sorry, I am pretty much a beginner in Go.

I have the following code in a server class at the moment:

package server

import "fmt"

type serverStarter interface {
	StartServer()
}

type Webserver struct{}

func (w Webserver) StartServer() {
	fmt.Printf("Starting server at port 8080\n")
}

func justATest() {
	Webserver.StartServer()
}

Here I get the error:,server.go:18:24 not enough arguments in call to Webserver.StartServer"

What arguments does it want? The StartServer Method has no Arguments, just a receiver type, if I see it right?

Do I have to initialize my Webserver first?

like with ,w Webserver" and then call the Method on w?
But how do I initialize an empty struct type.

I took an empty struct because I generally just want the type to have something for implementing the interface, maybe there is something better than an empty struct type to use.

I am just experimenting around, at the moment.

package main

import (
	"fmt"
)

func New() Webserver{
	return Webserver{}
}

type serverStarter interface {
	StartServer()
}

type Webserver struct{}

func (w Webserver) StartServer() {
	fmt.Printf("Starting server at port 8080\n")
}

func main() {
 	web := New()
	web.StartServer()
}

https://play.golang.org/p/iu-4IHdItir

3 Likes

Yep, you need an instance of the “Webserver” for access yours methods

That error message is a bit cryptic. It’s because Go has this feature where you don’t need to call member functions as if they’re methods; you could actually call them like functions, for example:

type MyStruct struct {
    I int
}

func (s MyStruct) GetI() int { return s.I }

s := MyStruct{I: 123}

i1 := s.GetI()
i2 := MyStruct.GetI(s)

Because you’re specifying a type and then a method name, the compiler assumes you’re writing a function call the second way and that you’ve missed the first parameter: The receiver type, Webserver.

You’re correct that you need a Webserver value first and then you can call your StartServer method on it. The way you create a value of any struct type is:

typename{ (optional field values) }

The empty struct is no different, other than there are no possible optional field values, so it’s always just typename{}. So to create a Webserver value and call StartServer on it, you can write Webserver{}.StartServer().

Your usage of the empty struct is perfect in this scenario. Zero-sized types such as empty structs, and 0-element arrays are often used to communicate that a type’s only purpose is to implement an interface. If you didn’t need to implement an interface, then you could have just create top-level functions.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.