When an identifier starts with a lowercase letter, the identifier is unexported or unknown to code outside the package.
When an identifier starts with an uppercase letter, it’s exported or known to code outside the package.
The New
function is returning a value of the unexported type alertCounter
, and main
is able to accept that value and
create a variable of the unexported type.
//counters/counters.go
//-----------------------------------------------------------------------
package counters
type alertCounter int
func New(value int) alertCounter {
return alertCounter(value)
}
//listing68.go
//-----------------------------------------------------------------------
package main
import (
"fmt"
"counters"
)
func main() {
counter := counters.New(10)
fmt.Printf("Counter: %d\n", counter)
}
This is possible for two reasons:
- identifiers are exported or unexported, not values.
the short variable declaration operator is capable of inferring the type and creating a variable of the unexported type.
You can never explicitly create a variable of an unexported type, but the short variable declaration operator can.