Why can not you not call an Interface function on a newly created instance of a struct that implements that Interface?

Why does

builder := aliasBuilder{}
 return builder.From(c.GetString("from")).To(c.GetString("to"))

compile and work but

return aliasBuilder{}.From("this").To("that") //<- does not work?

and if there is a way to make the one line version “work” what would that syntax look like?

Below is the code in more context.

type Alias struct {
	From uuid.UUID
	To   uuid.UUID 

func Create(c *gin.Context) domain.Alias {
  	builder := aliasBuilder{}
   	return builder.From(c.GetString("from")).To(c.GetString("to"))

type aliasBuilder struct {
	from uuid.UUID
	tb toBuilder

type toBuilder struct {
	fb *aliasBuilder
	touid uuid.UUID

type to interface {
	To(to string) uuid.UUID

type from interface {
	From(from string) to

func (fb *aliasBuilder) From(from string) *toBuilder {
	fb.from = uuid.FromStringOrNil(from)
	fb.tb = toBuilder{fb: fb}
	return &fb.tb

func (tb *toBuilder) To(tot string) domain.Alias {
	tb.touid = uuid.FromStringOrNil(tot)
	return domain.NewAlias(tb.fb.from, tb.touid)

Because your interface requires a pointer receiver and a struct literal can’t be used as a pointer receiver.

So how should I specify it to get the syntax that I want.

return aliasBuilder{}.From("this").To("that")

Change your implementation to use a not-pointer-receiver, eg:

func (tb toBuilder) To(tot string) domain.Alias {
    // ...

In addition to what NobbZ suggested, you could also say:

return (&aliasBuilder{}).From("this").To("that")

For example:



Thanks for taking the time to explain this. It is tricky getting the reference/dereferencing correct inline.

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