V语言05构

struct Point {
	x int
	y int
}

mut p := Point{
	x: 10
	y: 20
}
println(p.x) //用.访问
p = Point{10, 20}
assert p.x == 10

构分配在上,在上分配并取其引用,要加个&.

struct Point {
	x int
	y int
}

p := &Point{10, 10}//引用
//引用一样用.访问字段
println(p.x)

p类型为&Point,点引用,引用C++引用一个意思.引用就是常指针.
嵌入构,V不允许继承,但可嵌入.又在抄D的行为了.

struct Widget {
mut:
	x int
	y int
}

struct Button {
	Widget
	title string
}//D是插件.

mut button := Button{
	title: "点我"
}
button.x = 3

无嵌入,则要这样访问button.widget.x = 3.

默认字段值

struct Foo {
	n   int    // n默认是0
	s   string // s默认是""
	a   []int  // a默认是`[]int{}`
	pos int = -1 //自定义默认值
}

创建字段时,默认均为0值,并分配数组与映射,这点与D不一样.
要求字段:

struct Foo {
	n int [required]//要求
}

要求表明,创建构实例时,必须初化该字段,_ = Foo{}不会编译.

struct Point {
	x int
	y int
}

mut p := Point{
	x: 10
	y: 20
}
//省略构名
p = {
	x: 30
	y: 4
}//xy作为参数.
assert p.y == 4
//
//数组,第1个元素定义元素类型
points := [Point{10, 20}, Point{20, 30}, Point{40, 50}]
//C++直接{{..},{}}不折腾.
println(points) // [Point{x: 10, y: 20}, Point{x: 20, y: 30}, Point{x: 40,y: 50}]

返回构字面或传递参数,也可省略名.
V没有默认及命名参数,可用尾构字面符号:

struct ButtonConfig {
	text        string
	is_disabled bool
	width       int = 70
	height      int = 20//默认
}

struct Button {
	text   string
	width  int
	height int
}

fn new_button(c ButtonConfig) &Button {
	return &Button{//与返回类型重复了.
		width: c.width
		height: c.height
		text: c.text
	}
}

button := new_button(text: "点我", width: 100)
//未置高,所以为默认值.替换
//new_button(ButtonConfig{text:"Click me", width:100})
//与C++的原位构造没啥区别
assert button.height == 20

仅对构作为最后参数时,管用.
字段默认为私&不变.可用公/变来改.

struct Foo {
	a int //私不变
mut:
	b int //私变
	c int //同上
pub:
	d int //公不变,只读
pub mut:
	e int //公,仅在父模块可变
__global:
	//连全局变量都抄袭d,真没意思
	f int //任意时,公可变,
}

内置模块中定义的

struct string {
    str &byte//外部不能访问,
pub:
    len int//只读字段,不必`取置/属性`.因为默认不变
}

为不变,

方法

struct User {
	age int
}

fn (u User) can_register() bool {
	return u.age > 16
}//有个`用户接收器`名字叫`u`.不用`本/自`.

user := User{
	age: 10
}
println(user.can_register()) // "假"
user2 := User{
	age: 20
}
println(user2.can_register()) // "真"

V中无,你可在类型上定义方法.方法是带接收参数的函数(就是C++第一个指针).接收器fn与方法名间.方法名与接收器必须在同一模块.

也支持嵌入

struct Rgba32_Component {
	r byte
	g byte
	b byte
	a byte
}

union Rgba32 {
	Rgba32_Component
	value u32
}

clr1 := Rgba32{
	value: 0x008811FF
}

clr2 := Rgba32{
	Rgba32_Component: {
		a: 128
	}
}

sz := sizeof(Rgba32)
unsafe {
	println("大小: ${sz}B,clr1.b: $clr1.b,clr2.b: $clr2.b")
}
//输出`大小: 4B, clr1.b: 136, clr2.b: 0`

访问必须放在不安全块中.嵌入构不一定按列举顺序存储.

posted @   zjh6  阅读(18)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示