获取结构名称而不获取包名称或指针

我有一个非常简单的代码,如下所示:


package chain_of_responsibility


import (

    "fmt"

    "reflect"

)


type CustomerBalanceRequest struct{

    CustomerName string

    Balance int

}


type BalanceRequest interface {

    Handle(request CustomerBalanceRequest)

}


type HeadEditor struct{

    Next BalanceRequest

}


func (h *HeadEditor) Handle(b CustomerBalanceRequest){

    if b.Balance < 1000 {

        fmt.Printf("%T approved balance for %v request. Balance: %v\n", h, b.CustomerName, b.Balance)

        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h), b.CustomerName, b.Balance)

        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h).String(), b.CustomerName, b.Balance)

        fmt.Printf("%v approved balance for %v request. Balance: %v\n", reflect.TypeOf(h).Name(), b.CustomerName, b.Balance)


    } else{

        h.Next.Handle(b)

    }

}

在 fmt.Printf 行上,我想打印 HeadEditor 类型的名称。我使用各种方法来实现这一点,这就是我的结果:


*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500

*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500

*chain_of_responsibility.HeadEditor approved balance for John request. Balance: 500

 approved balance for John request. Balance: 500

问题是在前 3 个 Printf 调用中,我可以获得类型的名称,但它们包括指针和包名称。有什么方法可以让我只获得没有包名称和指针的“HeadEditor”,当然除了字符串处理解决方案(例如从结果中删除 * 和包名称)。


PIPIONE
浏览 71回答 1
1回答

开满天机

你已经接近最后一个了。正如Name()的文档所述:// Name returns the type's name within its package for a defined type.// For other (non-defined) types it returns the empty string.您将返回空字符串,因为 whilechain_of_responsibility.HeadEditor是已定义的类型,*chain_of_responsibility.HeadEditor但不是。您可以使用以下命令从指针类型中获取类型Elem():// Elem returns a type's element type.// It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.因此,如果它并不总是一个指针,那么在调用之前您需要首先检查它是否是一个指针Elem()。或者,您可以通过反射来使代码变得更简单(并且可能更快),并为您的类型提供一个方法,该方法返回您想要用于每种类型的任何字符串,例如Type() string. 然后,您可以定义一个Typer接口来封装该方法。
打开App,查看更多内容
随时随地看视频慕课网APP