goindexingstring-literals

Is it possible to slice a string literal?


Can we slice a string literal like 'test'[0:3] in Go without loops in 1 line of code?


Solution

  • Yes.

    Slice expressions apply to strings, including string literals:

    For untyped string operands the result is a non-constant value of type string.

    package main
    
    import "fmt"
    
    func main() {
        b := "Hello, 世界"[1:3]
        fmt.Println(b) 
        // prints el
    }
    

    The usual caveat is that slicing a string works with the string bytes. If you slice across multi-byte runes, you'll get corrupted data:

    func main() {
        b := "Hello, 世界"[8:9]
        fmt.Println(b)
        // prints � and not 世
    }