Go type 在它看起来不应该的时候自动转换

标签 go types casting

抱歉标题不明确。基于创建一个新类型和一个采用该类型参数的函数,当我认为我应该这样做时,我没有遇到编译器错误。

例子:

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
}

似乎如果我在与 main 相同的包中编写类型和函数,一切都会像我预期的那样工作?就像,它抛出一个编译器错误。关于跨包类型强制,我是否遗漏了什么?

最佳答案

我们可以进一步简化这个例子(playground):

package main

type Foo string

type Bar int

func main() {
    var f Foo = "foo"
    var b Bar = 1

    println(f, b)
}

这在 spec's assignability section 中有解释.

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type is identical to T.
  • x's type V and T have identical underlying types and at least one of V or T is not a named type.
  • T is an interface type and x implements T.
  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
  • x is an untyped constant representable by a value of type T.

关于Go type 在它看起来不应该的时候自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39714950/

相关文章:

python - 如何在 Python 中转换对象

java - Java 中的向下转型

c# - 将 Excel 导入 ASP.NET 时的 OleDbDataAdapter 和列转换

go - 在Go语句“typesubscriber struct {…}”中,type有什么作用?

javascript - 在 golang 中实现响应式模板

haskell - 构造函数中的不可见/隐藏字段

c - 使用 typeof 建立单一数据类型

unit-testing - Golang单元测试: error conditions

go - 测试从 panic 中恢复

java - 如何解决不兼容类型错误?