
上QQ阅读APP看书,第一时间看更新
How to do it...
These steps cover writing and running your application:
- From your terminal/console application, create and navigate to the chapter3/dataconv directory.
- Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter3/dataconv or use this as an exercise to write some of your own code.
- Create a file called dataconv.go with the following contents:
package dataconv
import "fmt"
// ShowConv demonstrates some type conversion
func ShowConv() {
// int
var a = 24
// float 64
var b = 2.0
// convert the int to a float64 for this calculation
c := float64(a) * b
fmt.Println(c)
// fmt.Sprintf is a good way to convert to strings
precision := fmt.Sprintf("%.2f", b)
// print the value and the type
fmt.Printf("%s - %T\n", precision, precision)
}
- Create a file called strconv.go with the following contents:
package dataconv
import (
"fmt"
"strconv"
)
// Strconv demonstrates some strconv
// functions
func Strconv() error {
//strconv is a good way to convert to and from strings
s := "1234"
// we can specify the base (10) and precision
// 64 bit
res, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
fmt.Println(res)
// lets try hex
res, err = strconv.ParseInt("FF", 16, 64)
if err != nil {
return err
}
fmt.Println(res)
// we can do other useful things like:
val, err := strconv.ParseBool("true")
if err != nil {
return err
}
fmt.Println(val)
return nil
}
- Create a file called interfaces.go with the following contents:
package dataconv
import "fmt"
// CheckType will print based on the
// interface type
func CheckType(s interface{}) {
switch s.(type) {
case string:
fmt.Println("It's a string!")
case int:
fmt.Println("It's an int!")
default:
fmt.Println("not sure what it is...")
}
}
// Interfaces demonstrates casting
// from anonymous interfaces to types
func Interfaces() {
CheckType("test")
CheckType(1)
CheckType(false)
var i interface{}
i = "test"
// manually check an interface
if val, ok := i.(string); ok {
fmt.Println("val is", val)
}
// this one should fail
if _, ok := i.(int); !ok {
fmt.Println("uh oh! glad we handled this")
}
}
- Create a new directory named example.
- Navigate to example.
- Create a file main.go with the following contents. Be sure to modify the dataconv import to use the path you set up in step 2:
package main
import "github.com/agtorre/go-cookbook/chapter3/dataconv"
func main() {
dataconv.ShowConv()
if err := dataconv.Strconv(); err != nil {
panic(err)
}
dataconv.Interfaces()
}
- Run go run main.go.
- You could also run:
go build
./example
You should see the following output:
$ go run main.go
48
2.00 - string
1234
255
true
It's a string!
It's an int!
not sure what it is...
val is test
uh oh! glad we handled this
- If you copied or wrote your own tests, go up one directory and run go test. Ensure that all tests pass.