复合文字中缺少类型 [英] Missing type in composite literal

查看:42
本文介绍了复合文字中缺少类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type A struct {
    B struct {
        Some string
        Len  int
    }
}

一个简单的问题.如何初始化这个结构?我想做这样的事情:

Simple question. How to initialize this struct? I would like to do something like this:

a := &A{B:{Some: "xxx", Len: 3}} 

可能我遇到错误:

missing type in composite literal

当然,我可以创建一个单独的结构B并通过以下方式对其进行初始化:

Sure, I can create a separated struct B and initialize it this way:

type Btype struct {
    Some string
    Len int
}

type A struct {
    B Btype
}

a := &A{B:Btype{Some: "xxx", Len: 3}}

但是它没有第一种方法有用.有没有初始化匿名结构的捷径?

But it not so useful than the first way. Is there a shortcut to initialize anonymous structure?

推荐答案

可分配性规则允许使用匿名类型,导致另一种可能性,您可以保留A的原始定义,同时允许编写该类型的简短复合文字.如果您确实要求B字段使用匿名类型,我可能会写类似以下内容的

The assignability rules are forgiving for anonymous types which leads to another possibility where you can retain the original definition of A while allowing short composite literals of that type to be written. If you really insist on an anonymous type for the B field, I would probably write something like:

package main

import "fmt"

type (
        A struct {
                B struct {
                        Some string
                        Len  int
                }
        }

        b struct {
                Some string
                Len  int
        }
)

func main() {
        a := &A{b{"xxx", 3}}
        fmt.Printf("%#v\n", a)
}

游乐场

输出

&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}

这篇关于复合文字中缺少类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆