在Go语言中,减少冗余代码可以通过以下几种方法实现:
i
作为循环变量,而不是index
或iterator
。for i := 0; i < len(arr); i++ {
// 处理数组元素
}
strings.Join
而不是手动拼接字符串。package main
import (
"fmt"
"strings"
)
func main() {
strs := []string{"hello", "world"}
result := strings.Join(strs, " ")
fmt.Println(result)
}
type Predicate func(int) bool
func filter(numbers []int, predicate Predicate) []int {
var result []int
for _, num := range numbers {
if predicate(num) {
result = append(result, num)
}
}
return result
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
evenNumbers := filter(numbers, func(num int) bool {
return num%2 == 0
})
fmt.Println(evenNumbers)
}
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func main() {
rect := Rectangle{width: 3, height: 4}
circle := Circle{radius: 5}
fmt.Println("Rectangle area:", rect.Area())
fmt.Println("Circle area:", circle.Area())
}
type Shape interface {
Area() float64
}
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func main() {
shapes := []Shape{Rectangle{width: 3, height: 4}, Circle{radius: 5}}
for _, shape := range shapes {
fmt.Println("Area:", shape.Area())
}
}
通过遵循这些方法,你可以在Go语言中有效地减少冗余代码,提高代码的可读性、可维护性和可扩展性。