Compare string and byte slice in Go without copy

The Go Programming Language Specification

String types

A string type represents the set of string values. A string value is a (possibly empty) sequence of bytes. The predeclared string type is string.

The length of a string s (its size in bytes) can be discovered using the built-in function len. A string's bytes can be accessed by integer indices 0 through len(s)-1.

For example,

package main

import "fmt"

func equal(s string, b []byte) bool {
    if len(s) != len(b) {
        return false
    }
    for i, x := range b {
        if x != s[i] {
            return false
        }
    }
    return true
}

func main() {
    s := "equal"
    b := []byte(s)
    fmt.Println(equal(s, b))
    s = "not" + s
    fmt.Println(equal(s, b))
}

Output:

true
false

Starting from Go 1.5 the compiler optimizes string(bytes) when comparing to a string using a stack-allocated temporary. Thus since Go 1.5

str == string(byteSlice)

became a canonical and efficient way to compare string to a byte slice.

Tags:

Go