While your code lives in the main package, you can import and use code from other packages, the most common of which will be the Go standard library.
Go comes with a rich standard library full of useful packages you can import.
To use code from another package, you need to import it:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
The import "fmt" statement tells Go you want to use the fmt package.
Once imported, you access a package's functions using the package name, a dot, and the function name:
package main
import "fmt"
func main() {
fmt.Println("This uses the fmt package")
fmt.Print("So does this")
}
The pattern is: packageName.FunctionName()
You can import multiple packages using parentheses:
package main
import (
"fmt"
"strings"
)
func main() {
name := "goku"
upper := strings.ToUpper(name)
fmt.Println(upper)
}
// Output: GOKU
This is cleaner than writing multiple import statements.
The strings package provides functions for working with text:
package main
import (
"fmt"
"strings"
)
func main() {
// Convert to uppercase
fmt.Println(strings.ToUpper("hello")) // HELLO
// Convert to lowercase
fmt.Println(strings.ToLower("WORLD")) // world
// Check if string contains substring
fmt.Println(strings.Contains("Goku", "ok")) // true
// Count occurrences
fmt.Println(strings
The math package provides mathematical operations:
package main
import (
"fmt"
"math"
)
func main() {
// Power
fmt.Println(math.Pow(2, 10)) // 1024
// Square root
fmt.Println(math.Sqrt(16)) // 4
// Absolute value
fmt.Println(math.Abs(-42)) // 42
// Maximum of two numbers
fmt.Println(math
The name you use to call functions matches the import path:
import "fmt" // Use as: fmt.Println()
import "strings" // Use as: strings.ToUpper()
import "math" // Use as: math.Pow()
Go will give a compilation error if you import a package but don't use it:
package main
import "fmt"
import "strings" // ERROR: imported and not used
func main() {
fmt.Println("Hello")
// Not using strings, so this causes an error
}
Only import what you actually need!
Here are some useful packages from Go's standard library:
fmt - Formatting and printingstrings - String manipulationmath - Mathematical operationsstrconv - Converting strings to/from other typestime - Working with dates and timesos - Operating system functionalityFor this challenge, use the strings and math packages together.
Your task:
fmt, math and strings packagesstrings.ToUpper() function to convert the name parameter in the first function to uppercase and return itmath.Sqrt() function to convert the powerLevel parameter in the second function to it's sqrt and return it.