tipos de datos de idiomas Ir hay?
1. Los tipos de datos básicos:
Constantes, enteros, punto flotante, números complejos, cadenas, booleanos
El tipo de datos compuesto:
Arrays, rebanadas, mapa, estructura, JSON ......
Hoy, quiero el registro
Debido a que los tipos de datos básicos en varios idiomas, básicamente, gramática y uso son similares, por lo que el registro enfoque qué tipo de uso de datos complejos.
texto
1. matriz
Una matriz es una secuencia de elementos de tipo particular, compuestos de una longitud fija, que puede estar compuesto de un conjunto de cero o más elementos, y la longitud de la matriz es fija. Debido a que la matriz no es tan flexible, es generalmente secciones de uso, donde sólo una breve pocos gama de uso básico.
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)
}
Aquí también se describe la función de varios ápice fácilmente confundido, Atoi, Itoa
primer ápice, este es un tipo enumerado, el papel principal es concebible que tomar la iniciativa para lograr recuento + 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)
}
Siete días a la semana por lo que se convierte en el conmutador de valor correspondiente puede ser utilizado correspondiente a la entrada así saber qué día.
Itoa, Atoi justo lo contrario de estos dos, el primero se utiliza para el valor en una cadena, la cadena a este último valor
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
De hecho, el uso y las rebanadas en rodajas en la lista de Python es más o menos la misma, por lo que la charla principal sobre la función de agregación
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
Mapa puede de hecho ser entendida como pares de valores clave, similar al diccionario en Python (Python para obtener el tipo de pitón ejemplo sencillo, simplemente porque entendido bien)
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. estructura
Y el lenguaje C esencialmente el mismo, pero la estructura anidada (combinación) para lograr una buena herencia de programación orientada a objetos
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
La estructura de una lengua Ir rebanada en el proceso de clasificación se llama JSON (cálculo de referencias). Marshalling hecho llamando a la función json.Marshal. Esta representación compacta Aunque contiene toda la información, pero es difícil de leer. Con el fin de generar un formato legible, otra función produce ordenada json.MarshalIndent salida de sangría. La función tiene dos cuerdas prefijo adicional parámetro indica la sangría de cada fila y cada nivel de salida.
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)
}
resumen
Los principales tipos de datos complejos comunes son, básicamente, grabar un poco, hablar, aunque sólo simple, pero vistazo a los códigos de uso básico puede también ayuda a la introducción-go.