drduh44480 2015-03-02 19:31
浏览 73
已采纳

如何在结构文字中将布尔指针设置为true?

I have the function below which accepts a bool pointer. I'm wondering if there is any notation which allows me to set the value of the is field to true in the struct literal; basically without to define a new identifier (i.e. var x := true ; handler{is: &x} )

package main

import "fmt"

func main() {
    fmt.Println("Hello, playground")
    check(handler{is: new(bool) })
}


type handler struct{
    is *bool
}

func check(is handler){}
  • 写回答

3条回答 默认 最新

  • douji8347 2015-03-02 20:02
    关注

    You can do that but it's not optimal:

    h := handler{is: &[]bool{true}[0]}
    fmt.Println(*h.is) // Prints true
    

    Basically it creates a slice with one bool of value true, indexes its first element and takes its address. No new variable is created, but there is a lot of boilerplate (and backing array will remain in memory until the address to its first element exists).

    A better solution would be to write a helper function:

    func newTrue() *bool {
        b := true
        return &b
    }
    

    And using it:

    h := handler{is: newTrue()}
    fmt.Println(*h.is) // Prints true
    

    You can also do it with a one-liner anonymous function:

    h := handler{is: func() *bool { b := true; return &b }()}
    fmt.Println(*h.is) // Prints true
    

    Or a variant:

    h := handler{is: func(b bool) *bool { return &b }(true)}
    

    To see all your options, check out my other answer: How do I do a literal *int64 in Go?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了