附录6 V和Go基本语法参照

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

模块

module mymodule
package mymodule

导入模块

import os
import time as t
import time {now,Time}
import mymodule.submodule
import (
	"os"
  "time"
  "mymodule/submodule"
)

函数

fn add(x int, y int) int {
	return x + y
}
pub fn foo() (int, int) {
	return 2, 3
}
func add(x int, y int) int {
    return x + y
}
func Foo() (int, int) {
    return 2, 3
}

结构体

struct User {
	name string
pub mut:
	age  int
}
type User struct {
	name string
	Age  int
}

方法

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

hello world

fn main() {
  println('Hello World!')
}
package main
import "fmt"
func main() {
  fmt.Println("Hello World!")
}

切片初始化

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

追加元素到切片

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

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

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

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

contains := x in numbers
contains := false
for _, num := range numbers {
        if num == x {
            contains = true
            break
        }
    }

读取文件

import os
text := os.read_file(path)or{
  eprintln(err)
  return
}
import (
    "io/ioutil"
    "log"
)
b, err := ioutil.ReadFile(path)
if err != nil {
        log.Println(err)
        return
}
text := string(b)

测试函数

fn test_hello() {
    assert hello() == 'hello'
}
package greeter_test
import (
    "testing"
)
func TestHello(t *testing.T) {
    if Hello() != "Hello" {
        t.Fatalf("Hello() failed")

最后更新于