如果资源是结构的成员,何时以及如何关闭资源

Here is classical example of using defer:

conn, err = amqp.Dial(rabbitMqConnectionString)
if err != nil {
    panic(err)
}
defer conn.Close()

In my case the connection is the member of struct and I am using this connnection in the different functions:

type MyServer {
  conn *Connection
}

func (s *MyServer) Run() {
  s.conn, err = amqp.Dial(rabbitMqConnectionString)
  if err != nil {
    panic(err)
  }
}

func (s *MyServer) DoSomethingWithConnection() {
  // ...do something with connection
}

In this case I cannot use defer in the Run() method. But where and how do I need to close connection in this case ?

func (s *MyServer) Stop() {
    //Some teardown
   s.conn.Close()
}
func main(){
    var s *MyServer
    ...
    s.Run()
    defer s.Stop()
    s.DoSomethingWithConnection()
}

As you can see i streadway/amqp/integration_test.go, the function using a connexion is responsible for closing it:

if c := integrationConnection(t, "txcommit"); c != nil {
    defer c.Close()
    ...
}

with:

// Returns a connection to the AMQP if the AMQP_URL environment
// variable is set and a connection can be established.
func integrationConnection(t *testing.T, name string) *Connection {
    conn, err := Dial(integrationURLFromEnv())
    if err != nil {
        t.Errorf("dial integration server: %s", err)
        return nil
    }
    return loggedConnection(t, conn, name)
}

And:

func loggedConnection(t *testing.T, conn *Connection, name string) *Connection {
    if name != "" {
        conn.conn = &logIO{t, name, conn.conn}
    }
    return conn
}