Generic Functions in Go

As of Go 1.18 you can write a generic function Print as below: package main import ( “fmt” ) // T can be any type func Print[T any](s []T) { for _, v := range s { fmt.Print(v) } } func main() { // Passing list of string works Print([]string{“Hello, “, “world\n”}) // You can … Read more

How do I return a Filter iterator from a function?

Rust 1.26 fn filter_one(input: &[u8]) -> impl Iterator<Item = &u8> { input.iter().filter(|&&x| x == 1) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec<_> = filter_one(&nums).collect(); println!(“{:?}”, other); } Rust 1.0 fn filter_one<‘a>(input: &’a [u8]) -> Box<Iterator<Item = &’a u8> + ‘a> { Box::new(input.iter().filter(|&&x| x == 1)) } … Read more

C# Adding two Generic Values

There is no generic constraint that allows you to enforce operator overload. You may take a look at the following library. Alternatively if you are using .NET 4.0 you could use the dynamic keyword: public static T Add<T>(T number1, T number2) { dynamic a = number1; dynamic b = number2; return a + b; } … Read more