From charlesreid1

No edit summary
Line 3: Line 3:
The Go blog: strings, bytes, runes, and characters in Go: https://blog.golang.org/strings
The Go blog: strings, bytes, runes, and characters in Go: https://blog.golang.org/strings


==How Strings Work==
==How strings work in Go==


A string in Go is a read-only slice of bytes. A string can hold arbitrary bytes, it is not required to hold unicode/UTF-8/other format. That means that "characters" are not special types in Go; rather, strings refer to bytes.
A string in Go is a read-only slice of bytes. A string can hold arbitrary bytes, it is not required to hold unicode/UTF-8/other format. That means that "characters" are not special types in Go; rather, strings refer to bytes.


Indexing a string does not access characters - it accesses the individual bytes. So, when you store a character value in a string, you are storing the byte representation of that character at that point in time.  
Indexing a string does not access characters - it accesses the individual bytes. So, when you store a character value in a string, you are storing the byte representation of that character at that point in time.  
==String Functions==
To use string functions, you need to import strings:
<pre>
package main
import "strings"
func main() {
    fmt.Println(strings.ToUpper("Hello world!"))
}
</pre>
The functions provided by the strings package will then be available via, for example, <code>strings.ToUpper()</code>.
To make this a little easier, you can do something analogous to Python's <code>import X as Y</code>:
<pre>
package main
import s "strings"
func main() {
    fmt.Println(s.ToUpper("Hello world!"))
}
</pre>


==String Slices==
==String Slices==

Revision as of 09:09, 13 December 2018

Related: Rosalind/Problem 1A

The Go blog: strings, bytes, runes, and characters in Go: https://blog.golang.org/strings

How strings work in Go

A string in Go is a read-only slice of bytes. A string can hold arbitrary bytes, it is not required to hold unicode/UTF-8/other format. That means that "characters" are not special types in Go; rather, strings refer to bytes.

Indexing a string does not access characters - it accesses the individual bytes. So, when you store a character value in a string, you are storing the byte representation of that character at that point in time.

String Functions

To use string functions, you need to import strings:

package main

import "strings"

func main() {
    fmt.Println(strings.ToUpper("Hello world!"))
}

The functions provided by the strings package will then be available via, for example, strings.ToUpper().

To make this a little easier, you can do something analogous to Python's import X as Y:

package main

import s "strings"

func main() {
    fmt.Println(s.ToUpper("Hello world!"))
}


String Slices

See the Go/Slices page for notes on how array slices work.

Flags