concatenate strings in Go

Following along with a discussion on golang-nuts mailing list.


Go requires you to be explicit when making
allocations. The vector package provides support for Python-like
managed lists:
import "container/vector"

The vector package implements containers for managing sequences of elements. Vectors grow and shrink dynamically as necessary.

Some of the go spec pertaining to this discussion:
Making slices, maps and channels

Slices, maps and channels are reference types that do not require the extra indirection of an allocation with new. The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values (§The zero value).

Call Type T Result

make(T, n) slice slice of type T with length n and capacity n
make(T, n, m) slice slice of type T with length n and capacity m

make(T) map map of type T
make(T, n) map map of type T with initial space for n elements

make(T) channel synchronous channel of type T
make(T, n) channel asynchronous channel of type T, buffer size n
The arguments n and m must be of integer type. A run-time panic occurs if n is negative or larger than m, or if n or m cannot be represented by an int.

s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
s := make([]int, 10) // slice with len(s) == cap(s) == 10
c := make(chan int, 10) // channel with a buffer size of 10
m := make(map[string] int, 100) // map with initial space for 100 elements
Copying slices

The built-in function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Source and destination may overlap. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of arguments copied is the minimum of len(src) and len(dst).

1 comment:

  1. // most idiomatic concatenate slices
    func concat(a, b []string) []string {
    return append(a, b...)
    }

    ReplyDelete