Charlie Andrews
Charlie Andrews

Reputation: 1477

Golang gob: type not registered for interface:

So I have a type String that is an alias of string defined:

type String string

I then apply the following method to it:

func (s String) String() string {
    str := "'" + s + "'"
    return string(str)
}

I then try to send a struct containing a String over rpc and get the following error:

gob: type not registered for interface: dbUtils.String

I do not define any interfaces with the same name, so why does gob think this is an interface?

I got the same error with a similar type but solved it with gob.Register(otherType{}). This does not work with String, presumably because string is not an interface. I am somewhat new to go so please explain what is happening.

Upvotes: 2

Views: 7739

Answers (2)

Verran
Verran

Reputation: 4082

I think this may be a solution to what you're trying to accomplish:

package main

import (
    "fmt"
)

type String string

func main() {
    var s String = "Hello"
    fmt.Println(s) // calls String()
    s2 := "Hello"
    fmt.Println(s2) // operates as standard "string"
}

func (s String) String() string {
    str := s + " World!"
    return string(str)
}

Try it on The Go Playground.

Note that you have to explicitly declare the variable as a String. If you use the := assignment, it will assume it is a string and ignore the function.

Upvotes: 2

Phil P
Phil P

Reputation: 843

It should work with String, but make sure you're passing an instance of a String() object, not the identifier String. So use gob.Register(String(""))

Upvotes: 2

Related Questions