Library contents

Go string slice

Extract the first three characters of an ASCII department identifier.

A simple example

string slice

  1. Start with "abc"
  2. Do this Take the first two characters
  3. Result "ab"
The selected region includes a and b. The third character is outside it.
main.go
package main

import (
    "fmt"
)

func main() {
    value := "abc"
    fmt.Println(value[:2])
}
Output
ab

Syntax

Go syntax
value[:3]
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Read a department on a semester timetable

A semester timetable stores its department field inside a larger record. Read the designated portion without bringing along the separator or the room information that follows it.

From the programvalue := "BIO-204"
ResultBIO
main.go
package main

import (
    "fmt"
)

func main() {
    value := "BIO-204"
    fmt.Println(value[:3])
}
Output
BIO

The first three letters identify the department.

Advertisements

Read the carrier code from a parcel

A structured code contains a department, room or other routing field inside a longer label. Extract the exact portion needed by the receiving system and verify which boundary is excluded.

From the programvalue := "AIR:482"
ResultAIR
main.go
package main

import (
    "fmt"
)

func main() {
    value := "AIR:482"
    fmt.Println(value[:3])
}
Output
AIR

The colon and serial number lie outside the selected range.

Read a parcel sorting code

The depot scans a parcel marked NC-17. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?

GivenNC-17
Worked resultNC

What to watch for

A length and an exclusive end index can look alike when starting at zero. Check the API before using a nonzero starting position.

Documentation for string slice