gorecursiongoroutine

how to quit infinite recursive call in Go


newbie in go, i create a struct of interface so i can calls the underlying interface then transform in new method. when i called the struct method get errors: runtime: goroutine stack exceeds 1000000000-byte limit

inter.go

package inter

type Say interface {
    Hello() string
}

greetings.go

package greetings

import (
    "fmt"

    "example.com/inter"
)

type Greetings struct {
    Someone inter.Say
}

func (G Greetings) Hello() string {

    return fmt.Sprintf("Hello, %v", G.Hello())
}

user.go

package user

type User struct {
    Name string
    Age  int
}

func (U User) Hello() string {
    return U.Name
}

main.go

package main

import (
    "fmt"

    "example.com/greetings"
    "example.com/user"
)

func main() {
    usr := user.User{
        Name: "Lizzy",
        Age:  25,
    }

    grt := greetings.Greetings{Someone: usr}

    fmt.Println(grt.Hello())
}


Solution

  • type Greetings struct {
        Someone inter.Say
    }
    
    func (G Greetings) Hello() string {
        return fmt.Sprintf("Hello, %v", G.Hello())
    }
    

    Greetings.Hello mistakenly calls itself, where the intent appears to be to call the Hello implementation on the receiver's Someone field:

    func (G Greetings) Hello() string {
        return fmt.Sprintf("Hello, %v", G.Someone.Hello())
    } //                                 ^^^^^^^^^