V和Go基本语法代码参照

V和Go的基本语法代码参照,方便熟悉Go的开发者,快速了解V:

模块

  1. module mymodule
  1. package mymodule

导入模块

  1. import os
  2. import time as t
  3. import time {now,Time}
  4. import mymodule.submodule
  1. import (
  2. "os"
  3. "time"
  4. "mymodule/submodule"
  5. )

函数

  1. fn add(x int, y int) int {
  2. return x + y
  3. }
  4. pub fn foo() (int, int) {
  5. return 2, 3
  6. }
  1. func add(x int, y int) int {
  2. return x + y
  3. }
  4. func Foo() (int, int) {
  5. return 2, 3
  6. }

结构体

  1. struct User {
  2. name string
  3. pub mut:
  4. age int
  5. }
  1. type User struct {
  2. name string
  3. Age int
  4. }

方法

  1. fn (m &User) str() string {
  2. return 'name:$m.name,age:$m.age'
  3. }
  1. func (u User) str() string {
  2. return "name:"+u.name+","+"age:"+strconv.Itoa(u.Age)
  3. }

hello world

  1. fn main() {
  2. println('Hello World!')
  3. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("Hello World!")
  5. }

切片初始化

  1. numbers := [1, 2, 3, 4]
  1. numbers := []int{1, 2, 3, 4}

追加元素到切片

  1. numbers << 5
  1. numbers = append(numbers, 5)

过滤切片中满足条件的元素

  1. even := numbers.filter(it % 2 == 0)
  1. even := make([]int, 0)
  2. for _, num := range numbers {
  3. if num % 2 == 0 {
  4. even = append(even, num)
  5. }
  6. }

检查切片是否包含某个元素

  1. contains := x in numbers
  1. contains := false
  2. for _, num := range numbers {
  3. if num == x {
  4. contains = true
  5. break
  6. }
  7. }

读取文件

  1. import os
  2. text := os.read_file(path)or{
  3. eprintln(err)
  4. return
  5. }
  1. import (
  2. "io/ioutil"
  3. "log"
  4. )
  5. b, err := ioutil.ReadFile(path)
  6. if err != nil {
  7. log.Println(err)
  8. return
  9. }
  10. text := string(b)

测试函数

  1. fn test_hello() {
  2. assert hello() == 'hello'
  3. }
  1. package greeter_test
  2. import (
  3. "testing"
  4. )
  5. func TestHello(t *testing.T) {
  6. if Hello() != "Hello" {
  7. t.Fatalf("Hello() failed")