单个对象满足多个匿名结构或未命名接口

时间:2019-06-26 19:45:23

标签: go struct interface

是否有一种方法可以拥有一个未命名/被丢弃的匿名合成接口,这样我就不必创建显式命名的合成接口来嵌入单个结构中,而不再使用它了?

或者有一种方法可以使一个嵌入式结构满足一个结构中的多个匿名接口?

工作代码:

 ob<-c(77.89824, 170.36929, 90.88129, 141.22368, 174.07871,
 106.51393, 94.32576, 85.31712, 78.95808, 222.30143, 115.25760,
 85.84704, 165.33504, 72.06912, 38.94912, 90.88129, 167.18976, 
 125.85600, 141.22367, 104.65922, 131.95009, 81.07777, 
 64.12032,130.36032, 89.29152, 65.97504, 40.27392, 64.38529, 
 113.40288)

 tm<-c(38.94912, 40.27392, 64.12032, 64.38529, 65.97504, 72.06912,
 77.89824, 78.95808, 81.07777, 85.31712, 85.84704, 89.29152, 
 90.88129, 94.32576, 104.65922, 106.51393, 113.40288, 115.25760, 
 125.85600, 130.36032, 131.95009, 141.22367, 141.22368, 165.33504, 
 167.18976, 170.36929, 174.07871)    

 bs<-c(0.96523390, 0.93066061, 0.89634466, 0.86213300, 0.82769878,
 0.79311455, 0.75831596, 0.72311471, 0.68800759, 0.65245482, 
 0.61700818, 0.58163643, 0.51021060, 0.47393336, 0.43788203, 
 0.40203755, 0.36614804, 0.33059801, 0.29408090, 0.25820874, 
 0.22265365, 0.18803136, 0.15444785, 0.11931985, 0.08411248, 
 0.05098459, 0.01957279)

 prc<-c(0.956974397, 0.914559074, 0.872836231, 0.831624652, 
 0.790544222, 0.749700646, 0.709038330, 0.668364230, 0.628275180, 
 0.588180704, 0.548730882, 0.509909531, 0.433282681, 0.395329802, 
 0.358306283, 0.322222487, 0.286868665, 0.252670119, 0.218461386, 
 0.185847964, 0.154593177, 0.125303855, 0.098121311, 0.071199383, 
 0.046104574, 0.024746731, 0.007529233) 

 plot(tm,bs,type="l",col="red")
 lines(tm,prc,col="black")

 tinf<-quantile(ob,prob=1/3)
 tsup<-quantile(ob,prob=2/3)

 idxinf<-which(tm>=(tinf-5) & tm<=(tinf+5))
 infgrafico<-mean(prc[idxinf])
 idxsup<-which(tm>=(tsup-5) & tm<=(tsup+5))
 supgrafico<-mean(prc[idxsup])

 segments(tinf,0.03, tinf,infgrafico,col='black',lty=3,lwd=1)
 segments(min(tm),infgrafico, 
 tinf,infgrafico,col='black',lty=3,lwd=1)
 text(tinf,cex=1,y=0,col="black",font=2,"T1")
 segments(tsup,0.03, tsup,supgrafico,col='black',lty=3,lwd=1)
 segments(min(tm),supgrafico, 
 tsup,supgrafico,col='black',lty=3,lwd=1)
 text(tsup,cex=1,y=0,col="black",font=2,"T2") 

详细,但满足单个嵌入

type Aer interface {
    A()
}

type Ber interface {
    B()
}

// AB1 is a struct that requires embedding satisfying each Aer and Ber
type AB1 struct {
    Aer
    Ber
}

这行不通,但这对我的用例来说是理想的

type ABer interface{
     Aer
     Ber
}

type AB2 struct {
    ABer
}

我了解,在大多数情况下,允许人们发送两次以嵌入同一对象或创建组合界面是一种最佳做法,但是我的大多数用例都是一次性的,并且从不使用。

下面是一个示例,显示了前两个的定义不同,但是在我的用例中行为类似,但是第三个是不起作用的:

type AB3 struct {
    // non-functioning code
    _ interface{
        Aer
        Ber
    }
}

0 个答案:

没有答案