Strings and Runes

Strings

Strings are enclosed in ". They can be joined with +

Examples:

Strings

a := "The jolly brown fox"
var b string
b = "what did the fox say"

fmt.Println(b," : " , a)
fmt.Println(b + " " +a)

Multiline Strings

Multiline strings can be defined with backticks:

package main

import (
	"fmt"
)

func main() {

	multiline := `Hello Gophers
welcome to the fox!
`

	fmt.Printf("%s", multiline)
}

String pointer

In the AWS SDK and in the CDK string pointers are often used. Assign a string to a string pointer:

This is invalid: p = &"What did the fox say"

// Invalid
var p *string
p = &"What did the fox say"

You first need a string in a variable.

This is valid:

 var p *string
s := "What did the fix say"
p = &s
fmt.Println(*p)

Because you often need a string pointer from a string, the AWS SDK has a convenience function:

With the import:

import 	"github.com/aws/aws-sdk-go-v2/aws"

you can get a string pointer directly out of a string:

description := aws.String("posy oc server"),

Runes

A string is just a sequence of bytes. But as go source is always encoded in UTF-8, strings could use UTF-8. UTF-8 encoded Unicodes in between 1 and 4 bytes.

Different as in other languages strings are only enclosed in ". Runes on the other hand are encloses in '

So:

aString := "This is a string"
aRune   := 'This is a rune'

Be careful when you copy & paste code from websites, because sometimes the differences between the characters are difficult to see with the naked eye. Also when there are not visible spaces.

The rune type is an alias of int32.

Coding with AWS you seldom needs runes.

To see the difference:

package main

import (
        "fmt"
        "reflect"
)

func main() {

        rune := 'B'
        aString := "B"

        // See content, unicode and type
        fmt.Printf("Rune: %v , %c; Unicode: %U; Type: %s \n", rune, rune, rune, reflect.TypeOf(rune))
        fmt.Printf("String: %v , %c; Unicode: %U; Type: %s \n", aString, aString, aString, reflect.TypeOf(aString))

}

Gives:

go run main.go
Rune: 66 , B; Unicode: U+0042; Type: int32
String: B , %!c(string=B); Unicode: %!U(string=B); Type: string

Whith the formatting:

  • %v the value in a default format
  • %c the character represented by the corresponding Unicode code point
  • %U Unicode format: U+1234; same as “U+%04X”
  • reflect.TypeOf(variable) gives its type

See also

Source

See the full source on github.

Sources