mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-13 23:21:38 +00:00
good good study, day day up!
This commit is contained in:
44
vendor/gopl.io/ch12/format/format.go
generated
vendored
Normal file
44
vendor/gopl.io/ch12/format/format.go
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 332.
|
||||
|
||||
// Package format provides an Any function that can format any value.
|
||||
//!+
|
||||
package format
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Any formats any value as a string.
|
||||
func Any(value interface{}) string {
|
||||
return formatAtom(reflect.ValueOf(value))
|
||||
}
|
||||
|
||||
// formatAtom formats a value without inspecting its internal structure.
|
||||
func formatAtom(v reflect.Value) string {
|
||||
switch v.Kind() {
|
||||
case reflect.Invalid:
|
||||
return "invalid"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16,
|
||||
reflect.Int32, reflect.Int64:
|
||||
return strconv.FormatInt(v.Int(), 10)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16,
|
||||
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return strconv.FormatUint(v.Uint(), 10)
|
||||
// ...floating-point and complex cases omitted for brevity...
|
||||
case reflect.Bool:
|
||||
return strconv.FormatBool(v.Bool())
|
||||
case reflect.String:
|
||||
return strconv.Quote(v.String())
|
||||
case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:
|
||||
return v.Type().String() + " 0x" +
|
||||
strconv.FormatUint(uint64(v.Pointer()), 16)
|
||||
default: // reflect.Array, reflect.Struct, reflect.Interface
|
||||
return v.Type().String() + " value"
|
||||
}
|
||||
}
|
||||
|
||||
//!-
|
24
vendor/gopl.io/ch12/format/format_test.go
generated
vendored
Normal file
24
vendor/gopl.io/ch12/format/format_test.go
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
package format_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gopl.io/ch12/format"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) {
|
||||
// The pointer values are just examples, and may vary from run to run.
|
||||
//!+time
|
||||
var x int64 = 1
|
||||
var d time.Duration = 1 * time.Nanosecond
|
||||
fmt.Println(format.Any(x)) // "1"
|
||||
fmt.Println(format.Any(d)) // "1"
|
||||
fmt.Println(format.Any([]int64{x})) // "[]int64 0x8202b87b0"
|
||||
fmt.Println(format.Any([]time.Duration{d})) // "[]time.Duration 0x8202b87e0"
|
||||
//!-time
|
||||
}
|
Reference in New Issue
Block a user