搜尋
首頁後端開發Golanggolang 斷言是什麼

golang 斷言是什麼

Dec 10, 2019 am 09:37 AM
golang肯定

golang 斷言是什麼

Go語言裡面有一個語法,可以直接判斷是否是該類型的變數:value, ok = element.(T),這裡value就是變數的值,ok是bool類型,element是interface變量,T是斷言的類型。

如果element裡面確實儲存了T類型的數值,那麼ok回傳true,否則回傳false。

package main
 
import (
  "fmt"
)
 
type Order struct {
  ordId   int
  customerId int
  callback func()
}
 
func main() {
  var i interface{}
  i = Order{
    ordId:   456,
    customerId: 56,
  }
  value, ok := i.(Order)
  if !ok {
    fmt.Println("It's not ok for type Order")
    return
  }
  fmt.Println("The value is ", value)
}

輸出:

The value is  {456 56 <nil>}

常見的還有用switch來斷言:

package main
 
import (
  "fmt"
)
 
type Order struct {
  ordId   int
  customerId int
  callback func()
}
 
func main() {
  var i interface{}
  i = Order{
    ordId:   456,
    customerId: 56,
  }
  switch value := i.(type) {
    case int:
      fmt.Printf("It is an int and its value is %d\n", value)
    case string:
      fmt.Printf("It is a string and its value is %s\n", value)
    case Order:
      fmt.Printf("It is a Order and its value is %v\n", value)
    default:
      fmt.Println("It is of a different type")
    }
}

輸出:

It is a Order and its value is {456 56 <nil>}

golang的語言中提供了斷言的功能。 golang中的所有程式都實作了interface{}的接口,這意味著,所有的類型如string,int,int64甚至是自訂的struct類型都就此擁有了interface{}的接口,這種做法和java中的Object類型比較類似。那麼在一個資料經由func funcName(interface{})的方式傳進來的時候,也就意味著這個參數被自動的轉為interface{}的型別。

如以下的程式碼:

func funcName(a interface{}) string {
     return string(a)
}

編譯器將會傳回:

cannot convert a (type interface{}) to type string: need type assertion

此時,表示整個轉換的過程需要型別斷言。類型斷言有以下幾種形式:

直接斷言使用

var a interface{}
fmt.Println("Where are you,Jonny?", a.(string))

但是如果斷言失敗一般會導致panic的發生。所以為了防止panic的發生,我們需要在斷言前先進行一定的判斷。

value, ok := a.(string)

如果斷言失敗,那麼ok的值將會是false,但是如果斷言成功ok的值將會是true,同時value將會得到所期待的正確的值。範例:

value, ok := a.(string)
if !ok {
    fmt.Println("It&#39;s not ok for type string")
    return
}
fmt.Println("The value is ", value)

另外也可以配合switch語句進行判斷:

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T", t)       // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}

另外補充幾個go語言程式設計的小tips:

(1)如果不符合要求可以盡快的return(return as fast as you can),而減少else語句的使用,這樣可以更直觀一些。

(2)轉換型別的時候如果是string可以不用斷言,使用fmt.Sprint()函數可以達到想要的效果。

(3)變數的定義和申明可以用群組的方式,如:

var (
   a string
   b int
   c int64
   ...
)
import (
    "fmt"
    "strings"
    "net/http"
   ...
)

(4)函數邏輯比較複雜,可以把一些邏輯封裝成一個函數,提高可讀性。

(5)使用net/http套件和net/url套件的函數,可能會有url encode功能,需要注意。

PHP中文網,有大量免費的Golang入門教學,歡迎大家學習!

以上是golang 斷言是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

使用微服務體系結構的好處使用微服務體系結構的好處Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。