gil shelef
gil shelef

Reputation: 87

Is there a difference between constants defined inside a Go function vs ones defined at the top of a package?

Is there a difference, mainly in performance, between constants defined inside vs outside a function scope?

func (this *Person) SetDefaults() *Person{
    const (
        defaultFirstName = "first"
        defaultLastName  = "last"
    )

    //do stuff with constants
    return this
}

vs.

const (
    defaultFirstName = "first"
    defaultLastName  = "last"
)
func (this *Person) SetDefaults() *Person{
    //do stuff with constants
    return this
}  

Upvotes: 4

Views: 672

Answers (1)

David Budworth
David Budworth

Reputation: 11626

The only difference is scoping

Constants are simply swapped out at every reference during compilation.
So there's no difference at run time as to where it came from.

Upvotes: 7

Related Questions