search
HomeWeb Front-endHTML TutorialGo 学习笔记(四)- 复合数据类型_html/css_WEB-ITnose

跟 js 不一样,go 的数组是固定的,不过可以通过 Slice(切片)来截取或增加数组内容。数组的索引从 0 开始,到长度-1结束,数组长度通过 len 获取。

var a [3]int // 数组声明var b [3]int = [3]int{1, 2, 3} // 数组声明+初始化fmt.Printf("%v, %v, %#v\n", len(a), a[0], a)fmt.Printf("%v, %v, %#v\n", len(b), b[0], b)// 3, 0, [3]int{0, 0, 0}// 3, 1, [3]int{1, 2, 3}

数组未带初始化时,为该类型默认的零值。

a := [...]int{1, 2, 3} // 简化声明b := [...]int{2: -1}fmt.Printf("%v, %v, %#v\n", len(a), a[0], a)fmt.Printf("%v, %v, %#v\n", len(b), b[2], b)// 3, 1, [3]int{1, 2, 3}// 3, -1, [3]int{0, 0, -1}

省略号 ...是根据初始值个数来计算的的,可以方便我们修改数据。

Slice(切片)

Slice(切片)代表变长的序列,slice 的语法和数组很像,只是没有固定长度而已。

一个 slice 由三个部分构成:指针、长度和容量,内置的 len和 cap函数分别返回 slice 的长度和容量。

arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}a := arr[:]b := arr[:5]c := arr[5:]fmt.Printf("%v, %v, %#v\n", len(arr), cap(arr), arr)fmt.Printf("%v, %v, %#v\n", len(a), cap(a), a)fmt.Printf("%v, %v, %#v\n", len(b), cap(b), b)fmt.Printf("%v, %v, %#v\n", len(c), cap(c), c)// 10, 10, [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}// 10, 10, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}// 5, 10, []int{0, 1, 2, 3, 4}// 5, 5, []int{5, 6, 7, 8, 9}

或者直接创建 Slice 类型:

arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

注意, []里没写数组大小以及 ...,这是声明一个 Slice 类型。

slice 之间不能最 ==比较,唯一合法的比较操作是和nil比较。

arr := []int{1, 2, 3}arr = append(arr, 4, 5)b := []int{6, 7, 8}arr = append(arr, b...)fmt.Printf("%v, %v, %#v\n", len(arr), cap(arr), arr)// 8, 12, []int{1, 2, 3, 4, 5, 6, 7, 8}

通过 append添加 Slice 元素。

Map

它是一个无序的key/value对的集合,就类似 js 的对象字面量一样,只是带了类型。

a := make(map[string]int)a["aa"] = 11a["bb"] = 22b := map[string]int{  "aa": 11,  "bb": 22,}delete(b, "aa")fmt.Printf("%#v\n", a)fmt.Printf("%#v\n", b)// map[string]int{"aa":11, "bb":22}// map[string]int{"bb":22}

通过 make创建,或直接字面量创建 map,通过 delete删除指定键。

a := map[string]map[string]int{  "aa": {    "aaa": 111,  },  "bb": {    "bbb": 222,  },}fmt.Printf("%v\n", a)// map[aa:map[aaa:111] bb:map[bbb:222]]

嵌套的 map 也还好,就是声明部分比较长,键值的表示跟 js 的几乎一样。

结构体

这个概念是我大学的时候学 C 接触到的概念,之后就再也没接触了。。不过 go 的结构体还是比较简单直观的。

type Point struct {  X int  Y int}// 或者type Point struct {  X, Y int}

使用:

a := Point{11, 22} // 按值的顺序b := Point{Y: 11, X: 22} // 通过成员赋值fmt.Printf("%+v\n", a)fmt.Printf("%+v\n", b)// {X:11 Y:22}// {X:22 Y:11}

嵌入:

type Point struct {  X, Y int}type Circle struct {  Center Point  Radius int}type Wheel struct {  Circle Circle  Spokes int}

使用的时候要注意,不能直接填值,要跟类型一起填充。

a := Wheel{Circle{Point{11, 22}, 33}, 44}fmt.Printf("%+v\n", a)// {Circle:{Center:{X:11 Y:22} Radius:33} Spokes:44}

JSON

算是扩展说明了,因为只是 结构体 和 encoding/json包的应用。

结构体声明如下:

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"}},}data, err := json.Marshal(movies)if err != nil {  log.Fatalf("JSON marshaling failed: %s", err)}fmt.Printf("%s\n", data)// [{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingrid Bergman"]},{"Title":"Cool Hand Luke","released":1967,"color":true,"Actors":["Paul Newman"]},{"Title":"Bullitt","released":1968,"color":true,"Actors":["Steve McQueen","Jacqueline Bisset"]}]

json 数据里 Year 变成了 released,Color 变成了 color,而且 Color 为 false 时,json 数据里忽略了这个字段。

这是因为构体成员 Tag 所导致的,也就是 json:"released"和 json:"color,omitempty"控制的。

文本和HTML模板

乍一看跟 es6 的字符模板一毛一样。。其实还是有一点点小区别的。

const templ = `{{.TotalCount}} issues:{{range .Items}}=======================Number: {{.Number}}User: {{.User.Login}}Title: {{.Title | printf "%.64s"}}Age: {{.CreatedAt | daysAgo}} days{{end}}`

模板中标签中数据输出是以 .开头的字段,如果不是,那就是命令,例如 range开始 end结束的,就是个循环。

而 html 模板跟 text 模板唯一区别就是实体转义。

小结

复合数据类型,其实出了语法外,都是基本类型的各种组合。明天就是函数部分了,加油。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor