Introduction to Built-in Functions in Go

Welcome, intrepid coder! Are you ready to embark on a journey into the realm of Go's built-in functions? These robust tools can enhance the efficiency of your code, saving time and effort. Our goal is to familiarize ourselves with some of the most straightforward built-in functions in Go. Let's begin this adventure!

Much like the onboard computing systems that guide astronauts, Go's built-in functions serve as readily available tools for navigating various coding tasks at any given moment. They act as our guiding stars through the immense cosmos of programming.

Exploring Simple Go Built-in Functions: len()

Let's chart a course through Go's built-in functions:

The len() function gives the number of elements in a slice, string, array, or the keys in a map, much like counting the stars in a constellation:

package main
import "fmt"

func main() {
    stars := []string{"star1", "star2", "star3", "star4"}
    fmt.Println(len(stars)) // Output: 4

    starMap := map[string]int{
        "star1": 1,
        "star2": 2,
        "star3": 3,
        "star4": 4,
    }
    fmt.Println(len(starMap)) // Output: 4

    starStr := "star1, star2, star3, star4"
    fmt.Println(len(starStr)) // Output: 26
}
Absolute Value: Abs()

Housed within the math package, the Abs() function gives the absolute value of a float64 number. It's much like a navigational device measuring a spaceship's distance from a specific point in space in light-years:

package main
import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.Abs(-10.00))  // Output: 10
    fmt.Println(math.Abs(7.00))    // Output: 7
}

Note that we import "math" here. We will need to import the "math" package for a wide range of math functions in Go, including the functions from the next section.

Float Numbers Rounding: Round(), Floor() and Ceil()

The Round(), Floor(), and Ceil() functions from the math package demonstrate how rounding a number to the nearest integer is achieved in Go. These functions operate similarly to rounding off estimated distances or times:

package main
import (
    "fmt"
    "math"
)
    
func main() {
    fmt.Println(math.Round(10.675))  // Output: 11
    fmt.Println(math.Floor(10.365))  // Output: 10
    fmt.Println(math.Ceil(7.5))  // Output: 8
}

Round() rounds the number according to math rules: any number is rounded to the nearest integer, and 0.5 is rounded up. Floor() rounds down to the nearest integer and Ceil() rounds up to the nearest integer.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal