这两门语言都是强类型的,不过rust由于其特有的Trait机制,使得咱可以在编写函数的时候不指定参数类型,取而代之只指定类型所具有的Trait。go语言中一般就只针对某种类型来编写函数。

咱举个例子,对比一下rust和go标准库中是如何比较bytes的。

Go


func Compare(a, b []byte) int {
    l := len(a)
    if len(b) < l {
        l = len(b)
    }
    if l == 0 || &a[0] == &b[0] {
        goto samebytes
    }
    for i := 0; i < l; i++ {
        c1, c2 := a[i], b[i]
        if c1 < c2 {
            return -1
        }
        if c1 > c2 {
            return +1
        }
    }
samebytes:
    if len(a) < len(b) {
        return -1
    }
    if len(a) > len(b) {
        return +1
    }
    return 0
}

Rust

// intermediate trait for specialization of slice's Ord
trait SliceOrd: Sized {
    fn compare(left: &[Self], right: &[Self]) -> Ordering;
}

impl<A: Ord> SliceOrd for A {
    default fn compare(left: &[Self], right: &[Self]) -> Ordering {
        let l = cmp::min(left.len(), right.len());

        // Slice to the loop iteration range to enable bound check
        // elimination in the compiler
        let lhs = &left[..l];
        let rhs = &right[..l];

        for i in 0..l {
            match lhs[i].cmp(&rhs[i]) {
                Ordering::Equal => (),
                non_eq => return non_eq,
            }
        }

        left.len().cmp(&right.len())
    }
}

/// Implements comparison of vectors lexicographically.
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Ord for [T] {
    fn cmp(&self, other: &[T]) -> Ordering {
        SliceOrd::compare(self, other)
    }
}

Ljzn
399 声望102 粉丝

网络安全;函数式编程;数字货币;人工智能