gopl-zh.github.com/vendor/gopl.io/ch3/printints/main.go

34 lines
629 B
Go
Raw Normal View History

2015-12-09 07:57:17 +00:00
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 74.
// Printints demonstrates the use of bytes.Buffer to format a string.
package main
import (
"bytes"
"fmt"
)
//!+
// intsToString is like fmt.Sprint(values) but adds commas.
func intsToString(values []int) string {
var buf bytes.Buffer
buf.WriteByte('[')
for i, v := range values {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%d", v)
}
buf.WriteByte(']')
return buf.String()
}
func main() {
fmt.Println(intsToString([]int{1, 2, 3})) // "[1, 2, 3]"
}
//!-