Home > database >  Why does the quote be used before definition in Golang
Why does the quote be used before definition in Golang

Time:10-26

I am studying Golang source code, I found codes

var DefaultServeMux = &defaultServeMux

var defaultServeMux ServeMux

the quote is used before definition, I wrote a sample code like this but got error:

func main(){
    type ServeMux struct {
        hosts string
    }
    var DefaultServeMux = &defaultServeMux
    var defaultServeMux ServeMux
    fmt.Printf("print [%s]\n", DefaultServeMux.hosts)
}

I got undefined: defaultServeMux

I want to know how can the codes compile successfully?

CodePudding user response:

The first piece of code shows two package level variable declarations. Package level variable declarations are evaluated before main starts running based on the order imposed by dependencies. Because of this, in the first snippet, defaultServeMux is declared and initialized before DefaultServeMux.

When you declare variables in a function, they are evaluated in the order they are defined. Because of this, in the second code snippet, at the point where DefaultServeMux is declared, defaultServeMux is not yet defined.

  •  Tags:  
  • go
  • Related