让'go test -run <case>'成功成为'go test'的一般规则是什么?

I found the 'go test' PASS, but if I specific sub test, it will fail, here I give a global variable sample, 'go test' will PASS, and 'go test -run f/sample2' will FAIL.

I'm wonder what's the general rules should I follow to prevent such problems?

t.go

package main

import "fmt"

var g string

func f(s string) string {
        g = g + s
        return s + g
}
func main() {
        fmt.Println(f("a"))
}

t_test.go

package main

import (
        "testing"
)

func Test_f(t *testing.T) {
        tests := []struct {
                name string
                g    string
                s    string
                r    string
        }{
                {"simple", "g1", "s1", "s1s1"},
                {"simple2", "g2", "s2", "s2s1s2"},
                {"simple3", "g3", "s3", "s3s1s2s3"},
        }
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
                        //g = tt.g
                        r := f(tt.s)
                        if r != tt.r {
                                t.Error("r=", r, "expect r=", tt.r)
                        }
                })
        }
}

If global variable is the problem, I often write something like osExit fmtPrint to replace os.Exit and fmt.Print on testing, how to overcome these?

The way to prevent such problems is to not have tests that depend on each other. In your case, the global variable is indeed a problem. If you run the tests in order, they have the expected global state. If you run them out of order, they don't, due to the inter-dependency between the tests.

The solution is to have each test work independently, by having it set up its own expected state. In this case, that would mean setting the global g variable to the expected value for each test.

A better solution is to refactor so you don't have global variables at all.