«
Go和Rust语言的核心语法特性

时间:2024-11   


由于篇幅限制,我将分别提供两个较长的代码示例,展示Go和Rust语言的核心语法特性。

Go语言示例

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// Person 结构体,展示结构体定义、方法和接口
type Person struct {
    Name string
    Age  int
}

// Greeter 接口
type Greeter interface {
    Greet() string
}

// Greet 方法实现接口
func (p *Person) Greet() string {
    return fmt.Sprintf("Hello, my name is %s and I'm %d years old.", p.Name, p.Age)
}

// 泛型函数示例
func Find[T any](slice []T, f func(T) bool) int {
    for i, v := range slice {
        if f(v) {
            return i
        }
    }
    return -1
}

// 错误处理示例
func checkError(err error) {
    if err != nil {
        panic(err)
    }
}

// 闭包示例
func makeGreeter(name string) func() string {
    return func() string {
        return fmt.Sprintf("Hello, %s!", name)
    }
}

// 并发示例
func worker(id int, wg *sync.WaitGroup, jobs <-chan int, results chan<- int) {
    defer wg.Done()
    for job := range jobs {
        fmt.Printf("Worker %d started job %d\n", id, job)
        time.Sleep(time.Second) // 模拟工作
        results <- job * 2
    }
}

func main() {
    // 切片、映射和范围循环
    names := []string{"Alice", "Bob", "Charlie"}
    ages := map[string]int{"Alice": 30, "Bob": 25, "Charlie": 35}

    for _, name := range names {
        fmt.Println(name)
    }

    // 接口和多态
    var greeters []Greeter
    for name, age := range ages {
        p := &Person{Name: name, Age: age}
        greeters = append(greeters, p)
    }
    for _, greeter := range greeters {
        fmt.Println(greeter.Greet())
    }

    // 泛型函数使用
    index := Find(names, func(s string) bool { return s == "Bob" })
    fmt.Printf("Bob is at index %d\n", index)

    // 错误处理
    _, err := time.Parse("2006-Jan-02", "31-Feb-2023")
    checkError(err)

    // 闭包
    greeter := makeGreeter("Go")
    fmt.Println(greeter())

    // 并发
    const numJobs = 5
    jobs := make(chan int, numJobs)
    results := make(chan int, numJobs)
    var wg sync.WaitGroup

    for w := 1; w <= 3; w++ {
        wg.Add(1)
        go worker(w, &wg, jobs, results)
    }

    for j := 1; j <= numJobs; j++ {
        jobs <- j
    }
    close(jobs)

    go func() {
        wg.Wait()
        close(results)
    }()

    for result := range results {
        fmt.Println("Result:", result)
    }

    // 延迟执行
    defer fmt.Println("Program ended")

    // 选择语句
    select {
    case <-time.After(2 * time.Second):
        fmt.Println("Timeout")
    }
}

Rust 语言示例

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

// 结构体定义和实现
struct Person {
    name: String,
    age: u32,
}

impl Person {
    // 方法
    fn greet(&self) -> String {
        format!("Hello, my name is {} and I'm {} years old.", self.name, self.age)
    }
}

// 枚举类型
enum Status {
    Active,
    Inactive,
    Pending,
}

// 泛型函数和特征
trait Summable<T> {
    fn sum(&self) -> T;
}

impl<T: std::iter::Sum> Summable<T> for Vec<T> {
    fn sum(&self) -> T {
        self.iter().sum()
    }
}

// 错误处理
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("Division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

// 闭包
fn make_greeter(name: String) -> impl Fn() -> String {
    move || format!("Hello, {}!", name)
}

// 并发示例
fn worker(id: u32, jobs: Arc<Mutex<Vec<u32>>>, results: Arc<Mutex<Vec<u32>>>) {
    loop {
        let job = {
            let mut jobs = jobs.lock().unwrap();
            jobs.pop()
        };
        match job {
            Some(job) => {
                println!("Worker {} started job {}", id, job);
                thread::sleep(Duration::from_secs(1)); // 模拟工作
                let mut results = results.lock().unwrap();
                results.push(job * 2);
            }
            None => break,
        }
    }
}

fn main() {
    // 变量、可变性
    let mut x = 5;
    x = 6;
    println!("x is {}", x);

    // 结构体实例化和方法调用
    let person = Person {
        name: String::from("Alice"),
        age: 30,
    };
    println!("{}", person.greet());

    // 枚举
    let status = Status::Active;
    match status {
        Status::Active => println!("Active"),
        Status::Inactive => println!("Inactive"),
        Status::Pending => println!("Pending"),
    }

    // 泛型和特征
    let numbers = vec![1, 2, 3, 4, 5];
    println!("Sum: {}", numbers.sum::<i32>());

    // 错误处理
    match divide(10, 2) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }

    // 闭包
    let greeter = make_greeter("Rust".to_string());
    println!("{}", greeter());

    // 并发
    let jobs = Arc::new(Mutex::new(vec![1, 2, 3, 4, 5]));
    let results = Arc::new(Mutex::new(Vec::new()));

    let mut handles = vec![];
    for i in 0..3 {
        let jobs = Arc::clone(&jobs);
        let results = Arc::clone(&results);
        let handle = thread::spawn(move || worker(i, jobs, results));
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Results: {:?}", results.lock().unwrap());

    // 生命周期
    {
        let string1 = String::from("long string");
        let result;
        {
            let string2 = String::from("xyz");
            result = longest(string1.as_str(), string2.as_str());
        }
        println!("The longest string is {}", result);
    }
}

// 生命周期示例
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

这两个示例展示了Go和Rust的一些主要语法特性,包括结构体、方法、接口/特征、泛型、错误处理、闭包、并发等。请注意,因为篇幅限制,示例中省略了一些特性,如Rust中的所有权系统、借用检查等,但在实际的Rust编程中,这些是非常重要的概念。