登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-21 14:12:35 215浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《获取结构名称而不获取包名称或指针》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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

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”,当然除了字符串处理解决方案(例如从结果中删除 * 和包名称)。


解决方案


您已经接近最后一个了。正如 name() 的文档所述:

// name returns the type's name within its package for a defined type.
// for other (non-defined) types it returns the empty string.

您将返回空字符串,因为虽然 chain_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 接口来封装该方法。

到这里,我们也就讲完了《获取结构名称而不获取包名称或指针》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>