Update to gobook@c6d7a22edd03e7738c38d5baa2174ff325d8d863

This commit is contained in:
Alan Donovan
2015-10-28 14:20:59 -04:00
parent fce1727c4c
commit 30090035de
150 changed files with 8559 additions and 6 deletions
+47
View File
@@ -0,0 +1,47 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 91.
//!+nonempty
// Nonempty is an example of an in-place slice algorithm.
package main
import "fmt"
// nonempty returns a slice holding only the non-empty strings.
// The underlying array is modified during the call.
func nonempty(strings []string) []string {
i := 0
for _, s := range strings {
if s != "" {
strings[i] = s
i++
}
}
return strings[:i]
}
//!-nonempty
func main() {
//!+main
data := []string{"one", "", "three"}
fmt.Printf("%q\n", nonempty(data)) // `["one" "three"]`
fmt.Printf("%q\n", data) // `["one" "three" "three"]`
//!-main
}
//!+alt
func nonempty2(strings []string) []string {
out := strings[:0] // zero-length slice of original
for _, s := range strings {
if s != "" {
out = append(out, s)
}
}
return out
}
//!-alt