对于两个相同类型的变量,可以使用 *a = *b 替换指针值
package main
import (
"log"
)
type s1 struct {
id int
}
func (s *s1) replace(s2 *s1) {
*s = *s2
}
func test(s *s1, s2 *s1) {
s.replace(s2)
}
func main() {
s := &s1{1}
s2 := &s1{2}
log.Println(s, s2)
test(s, s2)
log.Println(s, s2)
}
结果是
2015/04/09 16:57:00 &{1} &{2}
2015/04/09 16:57:00 &{2} &{2}
对于不同类型但相同接口的两个变量,是否可以实现相同的目标?
package main
import (
"log"
)
type i interface {
replace(s2 i)
}
type s1 struct {
id int
}
func (s *s1) replace(s2 i) {
*s = *s2
}
type s2 struct {
id float64
}
func (s *s2) replace(s2 i) {
*s = *s2
}
func test(s i, s2 i) {
s.replace(s2)
}
func main() {
s := &s1{1}
s2 := &s2{2.0}
log.Println(s, s2)
test(s, s2)
log.Println(s, s2)
}
这不编译
./test.go:16: invalid indirect of s2 (type i)
./test.go:24: invalid indirect of s2 (type i)
相关分类