Go language data types are there?
1. The basic data types:
Constants, integer, floating point, complex numbers, strings, Boolean
The composite data type:
Arrays, slices, map, structure, JSON ......
Today, I want the record
Because the basic data types in various languages basically grammar and usage are similar, so the focus record what type of complex data usage.
text
1. Array
An array is a sequence of particular type elements composed of a fixed length, it may be composed of an array of zero or more elements, and the length of the array is fixed. Because the array is not so flexible, it is generally use sections, where only a few brief array of basic usage.
package main
import (
"fmt"
)
func main() {
//首先是简单的数组创建
//1.输入数组大小的创建
var a [3]int
var b [3]int=[3]int{1,2,3}
fmt.Println(a)
fmt.Println(b)
//2.不输入数组大小,只输入数组元素的创建
q := [...]int{1, 2, 3}
fmt.Println(q)
}
Here also describes the function iota of several easily confused, Atoi, Itoa
First iota, this is an enumerated type, the main role is conceivable to take the initiative to achieve count + = 1
package main
import (
"fmt"
)
type week int
const (
Sunday week = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func main() {
fmt.Println(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
}
Seven days a week so that it becomes the corresponding value switch may be used corresponding to the input well know what day.
Itoa, Atoi just the opposite of these two, the former is used to the value into a string, the string to the latter value
package main
import (
"strconv"
)
func main() {
i, err := strconv.Atoi("12345")
if err != nil {
panic(err)
}
i += 3
println(i)
s := strconv.Itoa(12345)
s += "3"
println(s)
}
2. Slice
In fact, usage and sliced slices in python list is roughly the same, so the main talk about append function
package main
import (
"fmt"
)
func main() {
var runes []rune
for _, r := range "Hello,World" {
runes = append(runes, r)
}
fmt.Printf("%q\n", runes)
}
package main
import "fmt"
func main() {
var y, z []int
for i := 0; i < 10; i++ {
z = appendInt(y, i)
fmt.Printf("%d cap=%d\t%v\n", i, cap(z), z)
y = z
}
var k []int
k = appendInt(k, 3, 5)
k = appendInt(k, k...)
fmt.Println(k)
var w []int
w = append(w, 3, 5)
w = append(w, w...)
fmt.Println(w)
}
//简单实现一个append
func appendInt(x []int, y ...int) []int {
var z []int
zlen := len(x) + len(y)
if zlen <= cap(x) {
z = x[:zlen]
} else {
zcap := zlen
if zcap < 2*len(x) {
zcap = 2 * len(x)
}
z = make([]int, zlen, zcap)
copy(z, x)
}
copy(z[len(x):], y)
return z
}
3.Map
Map may in fact be understood as key-value pairs, similar to the dictionary in python (python to get the type of python simple example simply because well understood)
package main
import (
"fmt"
"sort"
)
func main() {
ages := make(map[string]int)
ages["1"] = 22
ages["2"] = 21
ages["3"] = 23
for name, age := range ages {
fmt.Printf("%s:%d\n", name, age)
}
names := make([]string, 0, len(ages))
for name := range ages {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Printf("%s\t%d\n", name, ages[name])
}
//删除操作
//delete(ages, "1")
//fmt.Println(ages)
age, ok := ages["1"]
if !ok {
fmt.Printf("找不到该值")
} else {
fmt.Printf("找到了该人的年龄,age=%d", age)
}
}
4. structure
And c language essentially the same, but the nested structure (combination) to achieve a good inheritance of oop
package main
import (
"fmt"
"time"
)
type Employee struct {
ID int
Name, Address string
DoB time.Time
Position string
Salary int
ManagerID int
}
type address struct {
hostname string
port int
}
type Point struct {
X, Y int
}
type Circle struct {
Point
Radius int
}
type Wheel struct {
Circle
Spokes int
}
func main() {
var dilbert Employee
var employeeOfTheMonth *Employee = &dilbert
employeeOfTheMonth.Position += " (proactive team player)"
dilbert.Salary += 5000 //初始值都是0
position := &dilbert.Position
*position = "Senior " + *position
fmt.Printf("%s,%d\n", dilbert.Position, dilbert.Salary)
fmt.Printf("%s", employeeOfTheMonth.Position)
//结构体也可以作为map的key
hits := make(map[address]int)
hits[address{"golang.org", 443}]++
fmt.Println(hits)
var w Wheel
w.X = 8 // equivalent to w.Circle.Point.X = 8
w.Y = 8 // equivalent to w.Circle.Point.Y = 8
w.Radius = 5 // equivalent to w.Circle.Radius = 5
w.Spokes = 20
fmt.Printf("%#v\n", w)
//用下面这两种字面值也是可以的,结果是一样的
//w = Wheel{Circle{Point{8, 8}, 5}, 20}
//
//w = Wheel{
// Circle: Circle{
// Point: Point{X: 8, Y: 8},
// Radius: 5,
// },
// Spokes: 20, // NOTE: trailing comma necessary here (and at Radius)
//}
//
//fmt.Printf("%#v\n", w)
//// Output:
//// Wheel{Circle:Circle{Point:Point{X:8, Y:8}, Radius:5}, Spokes:20}
//
//w.X = 42
//
//fmt.Printf("%#v\n", w)
}
package main
import "fmt"
/*
继承
一个结构体嵌到另一个结构体,称作组合
匿名和组合的区别
如果一个struct嵌套了另一个匿名结构体,那么这个结构可以直接访问匿名结构体的方法,从而实现继承
如果一个struct嵌套了另一个【有名】的结构体,那么这个模式叫做组合
如果一个struct嵌套了多个匿名结构体,那么这个结构可以直接访问多个匿名结构体的方法,从而实现多重继承
*/
type Car struct {
weight int
name string
}
func (p *Car) Run() {
fmt.Println("running")
}
type Bike struct {
Car
lunzi int
}
type Train struct {
Car
}
func (p *Train) String() string {
str := fmt.Sprintf("name=[%s] weight=[%d]", p.name, p.weight)
return str
}
func main() {
var a Bike
a.weight = 100
a.name = "bike"
a.lunzi = 2
fmt.Println(a)
a.Run()
var b Train
b.weight = 100
b.name = "train"
b.Run()
fmt.Printf("%s", &b)
}
5.JSON
The structure of a slice Go language into JSON process is called marshalling (marshaling). Marshalling done by calling json.Marshal function. This compact representation Although contains all the information, but it is difficult to read. In order to generate a readable format, another function produces neat json.MarshalIndent indented output. The function has two additional prefix string parameter indicates the indentation of each row and each output level.
package main
import (
"encoding/json"
"fmt"
"log"
)
type Movie struct {
Title string
Year int `json:"released"`
Color bool `json:"color,omitempty"`
Actors []string
}
var movies = []Movie{
{Title: "Casablanca", Year: 1942, Color: false,
Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}},
{Title: "Cool Hand Luke", Year: 1967, Color: true,
Actors: []string{"Paul Newman"}},
{Title: "Bullitt", Year: 1968, Color: true,
Actors: []string{"Steve McQueen", "Jacqueline Bisset"}},
// ...
}
func main() {
data, err := json.Marshal(movies)
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
data2, err := json.MarshalIndent(movies, "", " ")
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data2)
}
to sum up
The main common complex data types are basically record a bit, though just simple talk, but look at those basic usage code can also help entry-go.