Day07(指针和结构体)
指针和结构体
指针
Go 语言指针与 C 语言指针不一样理解,一个指针变量指向了一个值的内存地址。
类似于变量和常量,在使用指针前你需要声明指针
示例
-
示例一:
func new(Type) *Type
说明 new()方法 返回值就是指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main
import (
"github.com/Cc360428/HelpPackage/UtilsHelp/logs"
)
func main() {
intType := new(int)
logs.Info(intType)
var intType1 *int
logs.Info(intType1)
var intType2 int
logs.Info(intType2)
}
1
2
3
2020/04/23 22:21:59.542 [I] [pointer.go:9] 0xc000012380
2020/04/23 22:21:59.566 [I] [pointer.go:11] <nil>
2020/04/23 22:21:59.566 [I] [pointer.go:13] 0
- 示例 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main
import (
"github.com/Cc360428/HelpPackage/UtilsHelp/logs"
)
func main() {
var a int = 20 // 声明实际变量
var ip *int // 声明指针变量
ip = &a // 将变量 a 的指针复制给 ip
logs.Info(&a)
logs.Info(ip) // 指针变量的存储地址
logs.Info(*ip) // 使用指针访问值
}
1
2
3
2020/04/23 22:30:34.230 [I] [pointer2.go:11] 0xc0000882d0
2020/04/23 22:30:34.273 [I] [pointer2.go:12] 0xc0000882d0
2020/04/23 22:30:34.273 [I] [pointer2.go:13] 2
结构体
基础语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main
import "github.com/Cc360428/HelpPackage/UtilsHelp/logs"
// User 用户结构体
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
Statuc bool `json:"statuc"`
}
func main() {
var user User
logs.Info(user)
logs.Info(User{"lcc", 18, "lcc@lcc.com", false})
var user2 User
user2.Age = 23
user2.Name = "Cc"
user2.Email = "Cc@cc.com"
user2.Statuc = true
logs.Info(user2)
logs.Info(user2.Age)
logs.Info(user2.Name)
}
1
2
3
4
5
2020/04/23 22:45:58.034 [I] [struct.go:15] { 0 false}
2020/04/23 22:45:58.061 [I] [struct.go:16] {lcc 18 lcc@lcc.com false}
2020/04/23 22:45:58.061 [I] [struct.go:22] {Cc 23 Cc@cc.com true}
2020/04/23 22:45:58.061 [I] [struct.go:23] 23
2020/04/23 22:45:58.061 [I] [struct.go:24] Cc
进阶
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
import "github.com/Cc360428/HelpPackage/UtilsHelp/logs"
// User 用户结构体
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
Statuc bool `json:"statuc"`
}
// InitUser 获取User
func (u *User) InitUser(name string) (*User, error) {
u.Name = name
return u, nil
}
func main() {
user := new(User)
user.Age = 6
user2, _ := user.InitUser("lcc")
logs.Info(user2)
}
1
2020/04/23 22:51:45.282 [I] [struct2.go:22] &{lcc 6 false}
This post is licensed under
CC BY 4.0
by the author.