我有如下结构:type Connect struct {     ClientID string `yaml:"clientid"`     Password string `yaml:"password"`     Timeout  time.Duration `yaml:"timeout"`}c1 := `    id: 'client1'    password: 'hhhhhhha'    timeout: 10    `c2 := `    id: 'client2'    password: 'llllllla'    timeout: '10'    `c3 := `    id: 'client3'    password: 'hhhhhhha'    timeout: 10s    `c4 := `    id: 'client4'    password: 'llllllla'    timeout: '10s'    `如上所示,Timeout的类型为time.Duration,默认单位为纳秒,但我想得到结果:c1 && c2有错误,c3 && c4有效(Timeout的配置必须具有unit)。如何为yaml重写UnmarshalYAML()方法?非常感谢。
                    
                    
                3 回答
 
                    
                    
                            翻翻过去那场雪
                            
                                
                            
                        
                        
                                                
                    TA贡献2065条经验 获得超14个赞
一种方法是为Timeout实现Unmarshaler接口的自定义类型创建一个方法,如果您不能使用以下UnmarshalYAML方法实现该功能Connect:
type Connect struct {
ClientID string `yaml:"clientid"`
Password string `yaml:"password"`
Timeout UnmarshalingTimeout `yaml:"timeout"`
}
type UnmarshalingTimeout time.Duration
func (ut UnmarshalingTimeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
// implement unmarshaling here
}
- 3 回答
- 0 关注
- 571 浏览
添加回答
举报
0/150
	提交
		取消
	