How does Go do string comparison?

后端 未结 2 1541
闹比i
闹比i 2020-12-28 12:35

http://golang.org/ref/spec#Comparison_operators

Go supports string comparison without any special functions. Does the Go runtime do work behind the scenes to make co

2条回答
  •  情深已故
    2020-12-28 13:35

    runtime/string.goc (go1.3):

    func eqstring(s1 String, s2 String) (v bool) {
        if(s1.len != s2.len) {
            v = false;
            return;
        }
        if(s1.str == s2.str) {
            v = true;
            return;
        }
        v = runtime·memeq(s1.str, s2.str, s1.len);
    }
    
    int32
    runtime·strcmp(byte *s1, byte *s2)
    {
        uintptr i;
        byte c1, c2;
    
        for(i=0;; i++) {
            c1 = s1[i];
            c2 = s2[i];
            if(c1 < c2)
                return -1;
            if(c1 > c2)
                return +1;
            if(c1 == 0)
                return 0;
        }
    }
    

    Note: The runtime· separator is a Unicode middle-dot, not a period.

提交回复
热议问题