Javapublic enum DetectionMethodEnum { PROCESS_HASH("process_hash", "進程Hash檢測"), private final String type; private final String desc;}Go:type DetectionMethod stringtype DetectionMethodInfo struct { MethodType string Desc string}const ( ProcessHash DetectionMethod = "PROCESS_HASH")var DetectionMethodMap = map[DetectionMethod]DetectionMethodInfo{ ProcessHash: { MethodType: "process_hash", Desc: "進程Hash檢測" }}
Java:map.get(key) or map.getOrDefault(key, defaultValue)Go:if value, ok := map[key] ; ok { // ...code}
注意,轉換為 *Struct 和 轉換為 Struct 并不等同。如果你的值是指針,那么轉換為結構體會報錯;反之亦然。
Java:if (detectResultBase instanceof MemBackdoorDetectResult) { MemBackdoorDetectResult detectResult = (MemBackdoorDetectResult) detectResultBase; // ...code}Goif memBackdoorDetectResult, ok := detectResultBase.(*result.MemBackdoorDetectResult) ; ok { // ...code}
Java 的 NullPointerException 在 Go 變成了 nil pointer reference。
有兩個小區別:
給定代碼如下:
func TestBasic(t *testing.T) { var arr []int = nil for i := range arr { fmt.Println(i) } var stu *Stu stu.SayHello() fmt.Println(stu.GetName())}type Stu struct { Name string}func (s *Stu) SayHello() { fmt.Println("hello")}func (s *Stu) GetName() string { return s.Name}
圖片
圖片
Go 的錯誤處理與 Java 也有較大區別。
換句話說,Go 的錯誤如果忽略又不打日志,程序就會毫無輸出,對排查很不方便。這意味著:Go 做處理處理會比較繁瑣,每一個方法如果有錯誤就應該拋出,每一個錯誤都必須決定是否處理,還是繼續往上拋。益處是:能夠培養縝密的錯誤處理習慣。像 Java 那樣隨意,肯定會遭到懲罰。
Go 錯誤處理的一些推薦做法:
不得不說, Go 的報錯真的是有點不知所云。咋一看,看半天都看不出什么問題,真是費眼睛!因此,我總結了些常見報錯類型,方便以后更快排查。
可能是有兩個重名類 DO。比如有兩個同名類 A 和 B,本來應當引用 A,結果引用了 B。
Cannot use 'oldModels' (type []"xxx/internal/common/dal/service".T) as the type []"github.com/samber/lo".T
有時,你會發現包里確實聲明了這個變量、實例或結構體,但 IDE 就是報錯,找不到。很可能方法里的局部變量與包名沖突了。如下所示,有一個包名 models,又聲明了一個 models 變量,當然找不到啦!這種問題肉眼很難察覺。就像 Javascript 里,前面聲明了一個 password 變量,后面不小心寫成了 passord ,javascript 是不會報錯的(現在不知道會不會,好久沒寫 js 了)。
圖片
reason 字段的上報數據與類型定義不一致。
圖片
通常是因為之前在某個類里引用了某個包,后面又刪除了這個包,或者更改了包的位置導致。
圖片
在 ”Go 包循環引用及對策[1] “ 一文里已經有講解過。
類似問題可能是方法簽名不一致,比如方法函數簽名有返回值而實際傳入函數無返回值
cannot use calc (variable of type func()) as async.Consumer value in argument to taskExecutor.SubmitTask
Function has both named and unnamed parameters '(ctx context.Context, []D)'
圖片
Go 沒有支持 lambda 表達式。寫慣了 Java 導致。
報錯:Invalid operation: func(key string) (*models.WhiteRuleDO,error) - (the operator - is not defined on func(key string) (*models.WhiteRuleDO, error))
Cannot use 'func(key string) (*models.WhiteRuleDO,error) ->' (type bool) as the type func(key string) (T, error)
圖片
return whiteRulesInner, nil 處 報錯:Cannot use 'whiteRulesInner' (type []T) as the type *models.WhiteRuleDO
實際上 h.beyondLoginWhiteRuleCache.GetWithLoader 要返回的是 []*models.WhiteRuleDO 而不是 *models.WhiteRuleDO。
whiteRules, err := h.beyondLoginWhiteRuleCache.GetWithLoader(cacheKey, func(key string) (*models.WhiteRuleDO, error) { // ..code whiteRulesInner, err := h.whiteRuleService.List(ctx, whiteRuleQuery.Convert(ctx)) if err != nil { return nil, err } return whiteRulesInner, nil })
使用 Unmarshal 反序列化時,結構體的字段必須是首字母大寫,才能賦值成功,否則是默認值。
err := json_utils.Unmarshal(record.Value, fr) 報錯 ReadVal: can not read into nil pointer, error found
這個錯誤信息 "ReadVal: can not read into nil pointer, error found" 指的是在使用 json_utils.Unmarshal 進行 JSON 反序列化時,嘗試將 JSON 數據解碼到一個未初始化(nil)的指針變量 fr 中。
在 Go 語言中,如果有一個指針類型變量,如 *SomeStruct,在調用 Unmarshal 方法對 JSON 數據進行反序列化前,你需要確保該指針已經指向了一個實際的結構體實例,而不是 nil。
圖片
報錯 reflect.Value.Interface: cannot return value obtained from unexported field or method
字段名需要改成首字母大寫。
func (e *ElementOperationHistoryDO) SetDetail(detail any) { if detail != nil { detailType := reflect.TypeOf(detail).String() struct_utils.SetFieldValue(detail, DetailType, detailType) e.DetailInfo = struct_utils.StructToMap(detail) }}func SetFieldValue(obj any, fieldName string, value any) { v := reflect.ValueOf(obj).Elem() if v.Kind() != reflect.Struct { return } field := v.FieldByName(fieldName) if !field.IsValid() { return } field.Set(reflect.ValueOf(value))}將 detailInfo := &models.FileElementOperationDetailInfo{ Fpath: v.FileResponseAgentParam.FileName,} 傳給 detail
圖片
internal/ids_detect/eventflow/ability/UnifiedSsdeepDetect.go:157:62: got 3 type arguments but want 2
函數聲明了 2 個泛型參數,卻傳入了 3 個泛型參數。
圖片
圖片
[1]Go 包循環引用及對策:https://www.cnblogs.com/lovesqcc/p/18077717
本文鏈接:http://www.www897cc.com/showinfo-26-80886-0.htmlGo 開發踩過的那些坑,你踩過幾個?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com