Interface conversion from one to another

I have a following example https://play.golang.org/p/xgvFRVIrOZr

package main

import (
	"fmt"
)

// Getter sets a string
type Getter interface {
	Get() string
}

// Setter sets a string
type Setter interface {
	Set(string)
}

// A is a demo struct
type A struct {
	s string
}

func (a A) Get() string {
	return a.s
}
func (a *A) Set(s string) {
	a.s = s
}

// NewGetter returns new Getter interface
func NewGetter() Getter {
	return A{s: "Hello World!"}
}

func main() {
	a := NewGetter()
	fmt.Println(a.Get()) // Prints Hello World!
	
	// Following does not work and it is ok.
	// a.(Setter).Set("Hello Earth!") // panic: interface conversion: main.A is not main.Setter: missing method Set
	
	// Following does not work and it is ok, but weird.
	// (&a).(Setter).Set("Hello Earth!") // build failed: invalid type assertion: (&a).(Setter) (non-interface type *Getter on left)
	
	// Following does not work, but wait, what works than?
	// var i interface{} = &a
	// i.(Setter).Set("Hello Earth!") // panic: interface conversion: *main.Getter is not main.Setter: missing method Set
	
	// Following works, but how is it different from the previous example?
	var j interface{} = &A{
		s: "Hello World!",
	}
	j.(Setter).Set("Hello Earth!")

}

My task is really simple, I want to convert a variable from one interface to another. Is there a way to do so?

P.S.

I know how to do that using a reflection, but I am looking for a more simpler solution, any ideas?

I’m not 100% sure I really understand what you are trying to do here…

But when you say: “My task is really simple, I want to convert a variable from one interface to another. Is there a way to do so?” maybe you are really wanting to convert from one type to another?

What I’m seeing in your code looks like a very strange way to use interfaces in my experience… Generally its recommended to avoid using interface{} and I really cant see why you would from your example.

Here are some good post for using interface for polymorphism… Which is what I’m guessing you are really trying to do?

https://golangbot.com/polymorphism/

http://www.golangprograms.com/go-language/interface.html

Please review this code with provided notes.

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

In the end, I don’t like the use of the word convert to one interface to the other. This is this more as, I want to store the concrete data stored inside of one interface inside another interface. The problem is that in your example, you are storing not the concrete value but the address to an interface value which is a real no no.

2 Likes

I have tried to show you more staying away from the Getter/Setter stuff with more notes.

https://play.golang.org/p/1np7xdMa9zZ

2 Likes

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