如何在方法中返回结构变量

This program does not compile. It shows that the Env method is not available on the struct sample on method call. I can access the Env variable directly in the main program, but I'm curious to know why this is not compiling.

package main

//Sample is a struct
type Sample struct {
    Env string
}

func main() {
    pa := &Sample{Env: "acd"}
    pa.call()
}

func (p *Sample) call() *Sample.Env {
    return &p.Env
}

Function types are defined by the keyword func, followed by an optional receiver, followed by the function name, the parameter list between parentheses (which may be empty), and the result list (which may be empty), and then the function body.

The result list (zero or more types) is the contract for what the function will return. It can be a list of types or a list of named parameters including their types.

In your function definition for call():

func (p *Sample) call() *Sample.Env {

Your result list does not meet this expectation. *Sample.Env is a pointer to the Env property of type Sample, but not a type itself.

Your function returns value &p.Env. If you modify your function signature so that the result list is simply the type of &p.Env, then your program will run. p.Env is a string, therefore &p.Env is a pointer to a string. *string is the type "pointer to a string." Therefore if you change your function signature to this your code will work:

func (p *Sample) call() *string {

See:

  1. Function Types
  2. Types

Post script

The return type of call() is *string -- that is, a pointer to a string. So to print it you simply dereference it to a string with the asterisk:

env := pa.call()
fmt.Printf("Env is %s
", *env)