1
對不明的標題。當我相信我應該基於創建一個新類型和一個接受該類型參數的函數時,我沒有收到編譯器錯誤。Go類型自動轉換,當它看起來不應該
的例子:
package search
//Some random type alias
type Search string
//Takes a string and returns Search
func NewSearch(s string) Search {
return Search(s)
}
//This is where things are getting weird
//Returns an int just for arbitrary testing
func PrintSearch(s Search) int{
return 5
}
現在我的假設是,如果我創建使用NewSearch
一個對象,我就可以將它傳遞給PrintSearch和擁有一切按預期運行,但如果我通過PrintSearch一個原始字符串,它不應該編譯。我沒有遇到這種行爲。
的主要代碼:
package main
import (
"fmt"
".../search" //no need to type the whole path here
)
func main() {
SearchTerm := search.NewSearch("Test")
StringTerm := "Another test"
fmt.Println(search.PrintSearch(SearchTerm)) // This should print 5
fmt.Println(search.PrintSearch(StringTerm)) // This should throw a compiler error, but it is not
}
好像如果我寫的類型和在同一個包爲主要功能,一切正常,我期望?如在,它會引發編譯器錯誤。有沒有我錯過了有關跨包裝類型強制?
你不需要轉換的類型時,它的分配:https://golang.org/ref/spec#Assignability – JimB
那麼,如果從'string'本身獲得相同的類型安全性,那麼'type Something string'的具體用例是什麼? – thisisnotabus
「x的類型V和T具有相同的基礎類型,並且V或T中的至少一個不是指定類型。」我引用JimB鏈接的文檔。搜索基礎類型是字符串,字符串是未命名類型。 – mpm