give thisw ruby program in golang: `class flattenarray; def self.flatten(ar); [] if ar.nil?; ar.flatten.compact; end; end` in go

Here's an equivalent implementation of the Ruby flattenarray class in Go:

main.go
package main

import (
	"fmt"
)

func flatten(ar []interface{}) []interface{} {
	if ar == nil {
		return []interface{}{}
	}

	var result []interface{}
	for _, elem := range ar {
		switch elem := elem.(type) {
		case []interface{}:
			result = append(result, flatten(elem)...)
		case nil:
			// Ignore nil values
		default:
			result = append(result, elem)
		}
	}

	return result
}

func main() {
	ar := []interface{}{[]interface{}{1, 2, []interface{}{3}}, 4, []interface{}{5, nil}, nil}
	fmt.Println(flatten(ar)) // Output: [1 2 3 4 5]
}
538 chars
31 lines

The flatten function takes an input array of type []interface{}, which allows us to accept the variety of different types that Ruby arrays can contain. The function recursively flattens the nested arrays and discards nil values, similar to the Ruby implementation. Finally, the main function demonstrates how to use the flatten function with a sample input array.

related categories

gistlibby LogSnag