Write a function which can recieve any type of channel

I want to get a function which can recieve any type of chan as arguments,
(eg. chan int, chan chan int, chan myType …),

ch := make(chan int, 1)
ch2:= make(chan chan int, 2)

is there any way?

Hi @moskong ,

A function with a type parameter is what you need:

func [T any](c chan T)() {}

This function uses a type parameter T that can be substituted by any type. The function parameter c is a chan of type T, which matches any channel type.

Playground link


Hi, @christophberger. Thanks for your help, it helps me a lot.
And today, I get a advanced problem, is there any way we can make it support any direction of chan? l try this but it seems not work.

func fn[T any, C chan T | <-chan T | chan<- T](o C)

I think a get a solution about the problem above

func fn[T any | chan T | <-chan T | chan<- T](o T)

Thanks, @moskong, for sharing your solution.

I am not sure why this would be necessary. The type parameter T any is satisfied by any channel type. A single type parameter of [T any] should be sufficient, or am I missing something?

Thanks a lot for help!

  • Sorry for my late reply. In my case, fn can’t handle chan<- T or <-chan T with chan T

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.