Implications of defining a struct inside a function vs outside?

To me the main drawback for a type defined in a function is that you cannot define methods on that type.

See this example https://play.golang.org/p/cgH01cRwDv6:

package main

import (
    "fmt"
)

func main() {
    type MyType struct {
        Name string
    }

    // You cannot define a method on your type
    // defined in a function, can you?

    func (m MyType) String() string {
      return m.Name
    }

    m := MyType{Name: "Hello, World!"}
    fmt.Println(m)
}

The above example will fail with the error prog.go:15:27: expected ';', found 'IDENT' string (and 1 more errors).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)