171 return false, "", err
172 }
173
174 switch outputWriter.(type) {175 case io.WriteCloser:
176 outputWriter.(io.WriteCloser).Close()
177 }
234// not support int64 on 32-bit platform
235func (m Max) IsSatisfied(obj interface{}) bool {
236 var v int
237 switch obj.(type) {238 case int64:
239 if wordsize == 32 {
240 return false
188// not support int64 on 32-bit platform
189func (m Min) IsSatisfied(obj interface{}) bool {
190 var v int
191 switch obj.(type) {192 case int64:
193 if wordsize == 32 {
194 return false
789
790func formatPattern(f interface{}, v ...interface{}) string {
791 var msg string
792 switch f.(type) {793 case string:
794 msg = f.(string)
795 if len(v) == 0 {
Instead of asserting the type every time in a switch
statement, assign the
result of type assertion to a variable and use it.
A type assertion provides access to an interface's underlying concrete value.
The following statement asserts that the interface value i
holds the concrete type
T
assigns the underlying T
value to the variable t
. The statement will trigger
panic if i
does not hold a T
.
t := i.(T)
Hence, the recommendation of using the result of type assertion is idiomatic and straightforward. Also, it saves from the following bad practice:
switch x.(type) {
case int:
// Triggers a panic as "x" doesn't hold
// concrete type "string" but "int"
fmt.Println(x.(string))
}
switch x.(type) {
case int:
fmt.Println(x.(int))
}
switch x := x.(type) {
case int:
fmt.Println(x)
}