DEV Community

Cover image for Strings in Golang
tcs224
tcs224

Posted on

Strings in Golang

In Go, a string is a slice of bytes. In programming languages strings are used to define text. Strings let you store any type of text.

Golang lets you define strings using quotes and :=. The simple example below defines a string in Go (your name) and outputs it using the Println function.

package main

import (
    "fmt"
)

func main() {
    name := "Trevor"
    fmt.Println(name)
}

The above program outputs "Trevor". To run it, save it as hello.go and run the command

go run hello.go

You can see some more string examples here

Individual characters

You can access individual characters as you would in C or Java. Use the brackets with the index. But there is one key point here.

If you try this:

fmt.Println(name[0])

It outputs the byte value. Instead, you want to output it as character "%c". You can use the Printf function:

    fmt.Printf("%c", name[0])

That makes this program:

package main

import (
    "fmt"
)

func main() {
    name := "Trevor"
    fmt.Printf("%c", name[0])
    fmt.Printf("%c",name[1])
    fmt.Printf("%c",name[2])
}

The above program abouts 'Tre'. The first 3 characters of the string.

To get the last character, you can't use name[-1]. Instead you use name[len(name)-1].

package main

import (
    "fmt"
)

func main() {
    name := "Trevor"
    fmt.Printf("%c", name[len(name)-1])
}

Related links:

Top comments (0)