In Go, a package can span multiple files. All code within the same package can access each other's functions, variables, and types - even when they're defined in different files. This is called "package scope."
Every Go file starts with a package declaration:
package main
When multiple files have the same package declaration, they're all part of the same package and share everything with each other.
Imagine you have a project with these files:
main.go:
package main
import "fmt"
func main() {
fmt.Println(characterName) // Using variable from fighter.go
displayStats() // Using function from fighter.go
}
fighter.go:
package main
import "fmt"
var characterName = "Goku"
func displayStats() {
fmt.Println("Power Level: 9000")
}
Even though characterName and displayStats() are defined in fighter.go, they're accessible in main.go because both files belong to package main.
When you run the program with go run ., Go compiles all .go files in the directory together as one package. This means:
main.go:
package main
import "fmt"
func main() {
goku := createFighter("Goku", 9000)
vegeta := createFighter("Vegeta", 8500)
winner := fight(goku, vegeta)
fmt.Println(winner, "wins!")
}
fighter.go:
package main
type Fighter struct {
Name string
PowerLevel int
}
func createFighter(name string, power int) Fighter {
return Fighter{Name: name, PowerLevel: power}
}
battle.go:
package main
func fight(f1 Fighter, f2 Fighter) string {
if f1.PowerLevel > f2.PowerLevel {
return f1.Name
}
return f2.Name
}
All three files work together as one package! The main.go file can use createFighter() from fighter.go and fight() from battle.go.
Splitting code across multiple files helps with:
Notice that you don't need to import anything to use code from other files in the same package:
// fighter.go
package main
var maxPower = 10000
// main.go
package main
import "fmt"
func main() {
fmt.Println(maxPower) // No import needed!
}
As long as both files are in package main, they share everything automatically.
For this challenge, you'll create a new file called player.go that defines variables which will be used by main.go.
main.go (already provided):
package main
import "fmt"
func main() {
fmt.Println("Player:", playerName)
fmt.Println("Level:", playerLevel)
fmt.Println("Health:", playerHealth)
}
player.go (your task):
Inside the player.go file, create three package level variables
playerName with the value "Goku"playerLevel with the value 9001playerHealth with the value 100