From c93bd34a2fe5ce1ef8eb2405781fec01dd5a3c60 Mon Sep 17 00:00:00 2001 From: Vinicius Silva Date: Fri, 29 Dec 2023 17:17:32 -0300 Subject: [PATCH] Structs code file implemented --- 11_structs/embedded_structs.v | 33 ++++++++++++++++++++++++++++++ 11_structs/methods_structs.v | 18 ++++++++++++++++ 11_structs/sample/noinit_structs.v | 8 ++++++++ 11_structs/sample/sample.v | 18 ++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 11_structs/embedded_structs.v create mode 100644 11_structs/methods_structs.v create mode 100644 11_structs/sample/noinit_structs.v create mode 100644 11_structs/sample/sample.v diff --git a/11_structs/embedded_structs.v b/11_structs/embedded_structs.v new file mode 100644 index 0000000..6bfc3fd --- /dev/null +++ b/11_structs/embedded_structs.v @@ -0,0 +1,33 @@ +struct Size{ +mut: + width int + height int +} + +fn (s &Size) area() int{ + return s.width * s.height +} + +struct Button{ + Size + title string +} + +pub fn main(){ + mut button := Button{title: 'Click me', height: 2} + button.width = 3 + + assert button.area() == 6 + assert button.Size.area() == 6 + println(button) + + mut button1 := Button{Size: Size{ + width : 34 + height: 10 + }} + + println(button1) + + button1.Size = Size{width: 2, height: 9} + println(button1) +} \ No newline at end of file diff --git a/11_structs/methods_structs.v b/11_structs/methods_structs.v new file mode 100644 index 0000000..e66c745 --- /dev/null +++ b/11_structs/methods_structs.v @@ -0,0 +1,18 @@ +struct User{ + age int +} + +fn (u User) can_register() bool{ + return u.age > 16 +} + +pub fn main(){ + + user1 := User{age: 10} + + println(user1.can_register()) + + user2 := User{age: 20} + + println(user2.can_register()) +} \ No newline at end of file diff --git a/11_structs/sample/noinit_structs.v b/11_structs/sample/noinit_structs.v new file mode 100644 index 0000000..dccda3e --- /dev/null +++ b/11_structs/sample/noinit_structs.v @@ -0,0 +1,8 @@ +import sample + +fn main(){ + //mut into1 := sample.Information{data: 'Sample'} + //println(into1) + info := sample.new_information('Sample information')! + println(info) +} \ No newline at end of file diff --git a/11_structs/sample/sample.v b/11_structs/sample/sample.v new file mode 100644 index 0000000..0c75d09 --- /dev/null +++ b/11_structs/sample/sample.v @@ -0,0 +1,18 @@ +module sample + +@[noinit] +pub struct Information{ + pub: + data string +} + +pub fn new_information(data string) !Information{ + + if data.len == 0 || data.len > 100{ + return error('data must be between 1 and 100 characters') + }else{ + return Information{ + data: data + } + } +} \ No newline at end of file