Convert c# function to golang using generics

I’m wondering what is the idiomatic way to create this function in go

        protected static T WaitForValue<T>(Func<T> act, T expectedVal, int timeout = 15000, int interval = 16)
        {
            if (Debugger.IsAttached)
                timeout *= 100;

            var sw = Stopwatch.StartNew();
            do
            {
                try
                {
                    var currentVal = act();
                    if (expectedVal.Equals(currentVal))
                    {
                        return currentVal;
                    }
                    if (sw.ElapsedMilliseconds > timeout)
                    {
                        return currentVal;
                    }
                }
                catch
                {
                    if (sw.ElapsedMilliseconds > timeout)
                    {
                        throw;
                    }
                }

                Thread.Sleep(interval);
            } while (true);
        }

I am sure if i fully understood what this method does but here it is a sample code and you can work on it.

package main

import (
	"fmt"
	"time"
)

func WaitForValue[T comparable](act func() T, expectedVal T, timeout int, interval int) T {
	to := int64(timeout)
	startTime := time.Now().Local()
	for {
		currentVal := act()
		if currentVal == expectedVal {
			return currentVal
		}
		t := time.Now()
		elapsed := t.Sub(startTime)
		if int64(elapsed) > to {
			return currentVal
		}
	}
}

func myFunc() string {
	return "Hello, World!"
}

func main() {
	expectadVal := "Hello, World!"
	result := WaitForValue[string](myFunc, expectadVal, 1500, 16)
	fmt.Println(expectadVal, "=", result)
}

HTH,
Yamil

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