mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 22:52:05 +00:00
good good study, day day up!
This commit is contained in:
47
vendor/gopl.io/ch4/nonempty/main.go
generated
vendored
Normal file
47
vendor/gopl.io/ch4/nonempty/main.go
generated
vendored
Normal 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
|
Reference in New Issue
Block a user