日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

我們優雅判斷 interface 是否為 nil

來源: 責編: 時間:2024-01-15 09:20:14 215觀看
導讀背景很久之前發過一篇文章:《10個令人驚嘆的Go語言技巧,讓你的代碼更加優雅》,這篇文章中第八點有一處錯誤的地方被認真的讀者發現了:圖片于是我有空之后,立馬重新看了那篇文章的內容,確實是存在讀者所說的問題。問題問題就

背景

很久之前發過一篇文章:《10個令人驚嘆的Go語言技巧,讓你的代碼更加優雅》,這篇文章中第八點有一處錯誤的地方被認真的讀者發現了:MpM28資訊網——每日最新資訊28at.com

圖片圖片MpM28資訊網——每日最新資訊28at.com

于是我有空之后,立馬重新看了那篇文章的內容,確實是存在讀者所說的問題。MpM28資訊網——每日最新資訊28at.com

問題

問題就在于下面這句話,文章也是有列出的:MpM28資訊網——每日最新資訊28at.com

即使接口持有的值為 nil,也不意味著接口本身為 nil。MpM28資訊網——每日最新資訊28at.com

但是在執行以下語句的時候,是有可能報 panic 的:MpM28資訊網——每日最新資訊28at.com

return reflect.ValueOf(x).IsNil()

而輸出也是非常明顯的指出錯誤:MpM28資訊網——每日最新資訊28at.com

panic: reflect: call of reflect.Value.IsNil on int Value

因為不可 nil 的 interface 是不能使用 reflect.Value.IsNil 方法。MpM28資訊網——每日最新資訊28at.com

那么問題就很好解決了。MpM28資訊網——每日最新資訊28at.com

解決方式

我們在執行 reflect.Value.IsNil 方法之前,進行一次判斷是否為指針即可:MpM28資訊網——每日最新資訊28at.com

func IsNil(x interface{}) bool { if x == nil {  return true } rv := reflect.ValueOf(x) return rv.Kind() == reflect.Ptr && rv.IsNil()}

重點在于 rv.Kind() == reflect.Ptr && rv.IsNil() 這段代碼。MpM28資訊網——每日最新資訊28at.com

這段代碼的作用:MpM28資訊網——每日最新資訊28at.com

  • 判斷 x 的類型是否為指針。
  • 判斷 x 的值是否真的為 nil。

下面我們使用幾種常見的數據類型來進行測試:MpM28資訊網——每日最新資訊28at.com

func IsNil(x interface{}) bool { if x == nil {  return true } rv := reflect.ValueOf(x) return rv.Kind() == reflect.Ptr && rv.IsNil()}func main() { fmt.Printf("int IsNil: %t/n", IsNil(returnInt())) fmt.Printf("intPtr IsNil: %t/n", IsNil(returnIntPtr())) fmt.Printf("slice IsNil: %t/n", IsNil(returnSlice())) fmt.Printf("map IsNil: %t/n", IsNil(returnMap())) fmt.Printf("interface IsNil: %t/n", IsNil(returnInterface())) fmt.Printf("structPtr IsNil: %t/n", IsNil(returnStructPtr()))}func returnInt() interface{} { var value int return value}func returnIntPtr() interface{} { var value *int return value}func returnSlice() interface{} { var value []string return value}func returnMap() interface{} { var value map[string]struct{} return value}func returnInterface() interface{} { var value interface{} return value}type People struct { Name string}func returnStructPtr() interface{} { var value *People return value}

我們先后使用了 int、*int、slice、map、interface{}、自定義結構體 來測試此 IsNil 方法。運行程序輸出為:MpM28資訊網——每日最新資訊28at.com

int IsNil: falseintPtr IsNil: trueslice IsNil: falsemap IsNil: falseinterface IsNil: truestructPtr IsNil: true

從測試結果來看,目前是符合我們對此方法的定位的。MpM28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-60935-0.html我們優雅判斷 interface 是否為 nil

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 如何在函數式編程中處理可變狀態和副作用?

下一篇: 麻了,這讓人絕望的大事務提交

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 从江县| 石泉县| 大庆市| 富顺县| 龙海市| 随州市| 三门峡市| 镇宁| 陇南市| 罗城| 九龙坡区| 蕉岭县| 获嘉县| 邹城市| 宝鸡市| 绥棱县| 教育| 红安县| 昔阳县| 凉城县| 锦州市| 开封市| 改则县| 翼城县| 磴口县| 建始县| 尚志市| 青海省| 平顶山市| 资阳市| 白河县| 沁水县| 五原县| 桑植县| 岳西县| 南投县| 永城市| 瓦房店市| 德惠市| 兴和县| 潮安县|