Known issues
This page lists specific bugs, each with a workaround. For the limits that come with running Go on .NET, and the rough spots real code hits today, see Limitations.
Each entry describes go2cs 1.26.11.2, the current release. Where an earlier release differs, the entry says so. Issues fixed in 1.26.11.2 that remain only in earlier releases are at the end of the page, under Issues in older versions.
Writes through the address of another package’s pointer or interface variable are lost
Taking the address of a variable that another package exports gives a pointer to the variable itself when its
type is a value type. When its type is a pointer or an interface (&otherpkg.ErrMissing, for an
ErrMissing error), the pointer refers to a copy, and so does the address of runtime.MemProfileRate and of a
variable declared with a two-argument //go:linkname.
Limitations describes the cases and the
workarounds.
Converting modernc sqlite for Windows needs a seed for libc’s largeInteger
A converted modernc.org/sqlite program on Windows panics the first time it opens a database in WAL mode when
libc was converted without a seed for its largeInteger type. A -recurse conversion of the
sqlite module seeds libc by itself. With go2cs 1.26.11.1 or earlier, and for a libc converted on its own, the conversion needs
-inline-arrays=modernc.org/libc#largeInteger. The panic names both delegate types:
panic: go2cs: func cookie 0x... holds a
System.Func<ж<libc_package+TLS>, uintptr, libc_package+largeIntegerᴛ1, uintptr, UInt32, Int32>,
which cannot be read as
System.Func<ж<libc_package+TLS>, uintptr, sqlite.lib.sqlite3_package+TLARGE_INTEGERᴛ1, uintptr, UInt32, Int32>
Go calls sqlite’s TLARGE_INTEGER and libc’s largeInteger one type. sqlite converts its spelling whole through
unsafe.Pointer, so it holds that struct’s arrays inline. libc never does, so without the seed its spelling keeps
golib’s array<T>, and the two are different C# types. A function word that libc builds over its own type is
then called through sqlite’s type, and the call fails. The seed makes libc lay the type out as sqlite does, so both
packages share one lift. A database that is never opened in WAL mode does not reach the call.
To avoid it, convert the sqlite module and libc together (-recurse). That is enough:
the run seeds libc’s largeInteger because sqlite admits the same struct, and emits what the flag emits. With go2cs
1.26.11.1 or earlier, also pass -inline-arrays=modernc.org/libc#largeInteger; the same value is harmless on other targets,
where libc declares no largeInteger. A libc converted on its own (as a separate package) is seeded by neither
route, so it needs the flag on every release, or sqlite on Windows hits the panic again when built against it.
Platforms the packages do not ship
The go.* packages ship win-x64, linux-x64, linux-arm64, osx-x64 and osx-arm64. A package
whose code differs by platform carries one folder per platform under runtimes/, and a platform without one gets
the Windows build in lib/. A build resolves its platform the way .NET does at run time, so linux-musl-x64
(Alpine) uses the linux-x64 folder. For a platform that resolves to no folder, the build reports it:
GO2CS3003, an error, on another operating system, or on Linux with another architecture: linux-riscv64 would run the Windows build, and thelinux-x64build makes x64 system calls. The message names the platform and the first package without a folder for it.GO2CS3004, a warning, on a Windows platform the packages do not ship (win-arm64): the Windows build is that operating system’s, so the program runs. What Go decides by architecture when the package was converted followsamd64.
A cross-build for a shipped platform from an unshipped host is not affected: it names its platform with
-r <rid> (RuntimeIdentifier), and that platform has its folder.
To avoid it, build for one of the five shipped platforms. A build that only needs to compile, and knowingly wants
the Windows build (a test harness that never runs the program, say), passes -p:GoAllowReferenceFlavor=true. The
program then runs the Windows build wherever it runs. The property counts only on the command line: set in a
project file it changes nothing, so a library cannot switch the check off for the projects that build it.
A portable app built on a shipped platform and then RUN on another one is out of the build’s sight. At start-up
it prints a warning on standard error instead: for another operating system, and for the Linux build on another
architecture (linux-x64 run on linux-arm64).
On arm64, a few standard-library members throw when called
The arm64 builds of the standard library, linux-arm64 and osx-arm64, have a few members that Go
implements in arm64 assembly and that have no managed body yet, so each throws when called: getisar0 and getpfr0
in internal/cpu; getisar0, getisar1, getpfr0 and getzfr0 in vendor/golang.org/x/sys/cpu; load_g,
save_g, spillArgs, unspillArgs, asmcgocall_no_g, emptyfunc, panicBounds and panicExtend in runtime;
and rawVforkSyscall in syscall. Most of them exist only in the arm64 builds; the rest are routines that the other
builds also leave without a body. On osx-arm64 the list is the same less rawVforkSyscall, which only linux has, plus
getMIDR in internal/cpu, which only linux calls.
To avoid it, do not call these members. All of them are internal to the standard library, so a program reaches one only through a standard-library path; if yours does, report the call path.
On macOS, a go statement past the system’s thread limit ends the program
By default each goroutine is an operating-system thread, and macOS caps how many threads one process may run. When a
program already has nearly that many goroutines alive, the next go statement throws
System.OutOfMemoryException, and the program ends unless something catches it. On the macOS 15 machines measured
the limit was about 2,000 goroutines on Apple silicon and about 3,000 on Intel; a Mac’s own limit is the
kern.num_taskthreads setting.
To avoid it, bound how many goroutines are alive at once, with a worker pool for example. Limitations has the details, under Goroutines are operating-system threads. Async twins, experimental and opt-in, lift the limit for goroutines that wait in twinned code.
On Linux, a program with more than about 16,000 goroutines alive ends
By default each goroutine is an operating-system thread, and on Linux each .NET thread uses about four of the process’s memory
mappings. Linux caps the mappings at the vm.max_map_count setting, 65,530 by default. When a program has about
16,000 goroutines alive (measured on linux-x64, Ubuntu 22.04 under WSL, at the default setting), the next go statement fails with Fatal error. Failed to create RW mapping for RX memory,
and the program ends; nothing can catch it. A Go goroutine is not a thread, so the limit does not apply to Go itself.
To avoid it, bound how many goroutines are alive at once, with a worker pool for example. Two settings may raise
the limit, but neither has been measured: DOTNET_EnableWriteXorExecute=0 in the environment, which should cut the
mappings each thread uses, and a larger vm.max_map_count on the machine.
Under async twins (experimental: build with twins and run with GO2CS_MN=1), a goroutine parked in a twin holds no
thread, so the limit counts only the goroutines blocked in calls the twins do not cover: a sync.Cond wait, a
Lock reached through a sync.Locker interface, a cgo or system call. About 16,000 of those blocked
at once end the program the same way (PAL_SEHException, then an abort); the same bound avoids it.
Goroutines on a shared pool of threads (M:N) are experimental, and off unless you build and run for them
By default each goroutine is an operating-system thread, which is what the two sections above describe. go2cs also has an experimental M:N scheduler, in which goroutines take turns on a small pool of threads as Go’s do (Async twins explains it and how to opt in). The scheduler is new in go2cs 1.26.11.2; go2cs 1.26.11.1 does not have it. It is inert unless both halves are switched on:
- The build: the projects are built with twins (async twins), an async copy of each function that can wait
without holding a thread. The
GoTwinsForproperty names the projects to build with twins, by project file name without.csproj, separated by;. Set it in the environment: on thedotnet buildcommand line each;must be written%3B, or MSBuild ends the property there.GoTwins=truein one project’s own file builds that project with twins, but a new conversion writes the file again and drops it. These properties are read by go.lib’s build files, so they work for any converted program, against a repository clone, adeploy-coreroot or thego.*packages. Thego.*packages carry their twins from 1.26.11.2; the 1.26.11.1 packages carry none (their go.gen has no twin generator), so a project that references them builds without twins whatever it sets. - The run: the environment sets
GO2CS_MN=1. How many goroutines run at once followsGOMAXPROCS, as in Go: theGOMAXPROCSenvironment variable at start, andruntime.GOMAXPROCS(n)while the program runs.GO2CS_MN_PROCS=<n>pins the count instead; it is a measurement switch, not a supported setting.
Without GO2CS_MN=1 a program built with twins runs on threads as usual, and runtime.GOMAXPROCS reads and sets the
value Go’s does but caps nothing: the operating system decides how many threads run at once. With it, a goroutine that
waits inside code built without twins keeps its thread while it waits. The other GO2CS_MN_* variables the scheduler
reads are measurement switches, not settings: none is supported, and they may change or go away. The diagnostics
GO2CS0014, GO2CS0015, GO2CS0017, GO2CS0018, GO2CS0019, GO2CS0020 and GO2CS0021 (Diagnostic codes) come only from a build with twins.
A plain read and a call in the same expression can see different values with and without twins. In an expression
such as fmt.Println(a, f()), Go orders only the calls: the read of a may come before or after f(), and the gc
compiler reads it after. The converted code reads operands left to right, as C# does, so when f changes a it prints
the value a had before the call. Built with twins and run with GO2CS_MN=1, a call that can wait is sometimes
evaluated ahead of the plain reads in its expression, as gc evaluates it, and then the program prints the value after
the call. Both orders are allowed by the Go specification; a program whose output depends on the difference relies on
unspecified behavior.
With twins this also happens when the statement calls another function before the call that can wait, in a compound
assignment (s += f() reads s after f), and when the value is converted to an interface for the call.
After a carrier stack could not be reserved, goroutines recurse to two depths. Under the M:N scheduler each carrier
thread reserves 1 GiB, or what a set GO2CS_GOROUTINE_STACK says (Tuning). A carrier
that cannot reserve its size, for instance because the carriers already running used up a commit or address-space
limit, starts at the largest size it gets, halving down to 1 MiB, and says so once on stderr; carriers started after it
take that size. Carriers started before it keep theirs, so a goroutine, main included, can recurse to the full depth
on one carrier and run out of stack at half of it on another, depending on which carrier resumes it.
A wait the scheduler cannot see holds its thread, and the scheduler adds threads around it, up to a ceiling. A
goroutine built with twins can still block somewhere golib does not see: a .NET wait in hand-written C# (lock, an
event, Task.Wait, Thread.Sleep), or a native call. The scheduler notices a .NET wait that lasts two of its ticks and
gives the goroutine’s processor to other work. For anything else it starts more threads while work waits. In all it
starts at most 10,000 threads (Go’s default; set it with debug.SetMaxThreads). A program
that needs more ends as Go’s does: runtime: program exceeds 10000-thread limit, then fatal error: thread exhaustion
and exit status 2.
Goroutines that only compute can make it add threads too, where Go adds none: it starts threads while compute work
waits for a processor, and more of them the more goroutines there are. So under GO2CS_MN=1 a program that lowers the
ceiling with debug.SetMaxThreads and starts hundreds of compute goroutines can end that way where Go finishes. Raise
the ceiling, or leave M:N off; with M:N off, the default, this does not happen.
C# that blocks in its own native call says so with GoNativeCall. Code you write in C# that calls a native
function which can block (a P/Invoke that waits on a device, a socket or a lock) brackets the call, so the scheduler
can give the goroutine’s processor away while it waits:
GoNativeCall.Enter(NativeCallHint.Blocks); try { Call(); } finally { GoNativeCall.Exit(); }. Blocks gives the
processor away at once, as Go’s entersyscallblock does; MayBlock, the default, keeps it and lets the scheduler take
it back if the call lasts. Call Exit exactly once for each Enter, on the same goroutine, and read the call’s error
(Marshal.GetLastPInvokeError) before Exit. GoNativeCall is an advanced member of go.golib: hidden from
completion, and frozen, so a program that uses it keeps working across releases. Without twins or without
GO2CS_MN=1 it does nothing.
A slice, array or string holds at most about 2.1 billion elements
A Go slice, array or string is backed by one .NET array, and a .NET array holds at most Array.MaxLength elements,
2,147,483,591. Go on a 64-bit machine allows more. The limit counts elements, not bytes, so a slice of larger elements
can pass 2 GB in total; a []byte or a string cannot.
- A
makewith a longer length or capacity panics with Go’s own recoverable message,makeslice: len out of rangeormakeslice: cap out of range, and anappendthat would grow a slice past the limit panics withgrowslice: len out of range. - A slice of a zero-size element, such as
[]struct{}, has no limit atmake, as in Go, but some operations on one that long panic with a message that names the limit. - Joining strings into one longer than the limit is not checked: it ends the program with a .NET
OutOfMemoryExceptionorOverflowException, whichrecovercannot catch.
Most programs that meet it hold a whole large file, or a decompressor’s whole output, in one []byte. To avoid
it, work in chunks, or stream through an io.Reader and io.Writer.
A nugetgo package built on 1.26.10.3 beside the go.* 1.26.11.1 packages fails at restore
Symptom. dotnet restore, or the restore a dotnet build starts with, stops with NU1107, a version conflict
on one go.* package (go.internal.bytealg, for one). The project references a nugetgo.* revision built on
1.26.10.3 and go.* packages at 1.26.11.1.
Cause. Each go.* package pins the go.* packages it depends on to its own exact version. A nugetgo.*
revision built on 1.26.10.3 accepts any go.* version from 1.26.10.3 up to 1.27.0. When nothing else in the project
asks for a newer version of one of those packages, NuGet takes the lowest, 1.26.10.3, and that package’s exact pins
conflict with the 1.26.11.1 pins of the go.* packages the project references. Restore fails before the build
runs, so the break-floor check, which would name the old package (GO2CS3002), is never reached.
Workaround. Move each nugetgo.* reference to its 1.26.11.1 revision, as
Upgrading from 1.26.10.3 says. A revision built on 1.26.10.3 is below the break floor in any case: if
you reference its go.* dependencies at 1.26.11.1 directly, restore succeeds and the build stops with
GO2CS3002, naming that package.
Building a converted project by a path that runs through a symbolic link can fail with MSB3202
go2cs writes the runtime root, $(go2csPath), as an absolute path. But most standard-library projects are reached
through other projects, and .NET’s restore and build record each of those as a path relative to your project; go2cs
does not write that path. When the path you give for the project runs through a symbolic link, the relative path is
counted from the link and walked from the real directory, so it ends in the wrong directory and those projects are
“not found” (error MSB3202). On macOS /tmp and the temporary folder ($TMPDIR, under /var) are such links.
To avoid it, give dotnet build the project’s real path, for example from pwd -P or realpath, or keep the
converted tree in a directory that is not reached through a link.
Ubuntu’s packaged .NET 10 can end a converted program early
On Ubuntu’s own build of .NET 10 (the dotnet installed with apt, runtime identifier ubuntu.*-x64), a
converted program that raises and recovers Go panics inside a hot loop can stop in one of two ways under the
default tiered compilation:
- a fatal
Internal CLR error. (0x80131506); - more often, a SILENT exit with code 0 and truncated output.
The fault needs the JIT’s on-stack replacement. Microsoft’s build of the same .NET version does not show it, and neither does Windows. No converted Go program is known to reproduce it; only a synthetic reproduction does.
To avoid it, run on Microsoft’s .NET build, or turn off quick JIT for loops, which removes on-stack replacement. A build property does it without touching the converted project:
dotnet build -p:TieredCompilationQuickJitForLoops=false
The built program’s runtimeconfig.json then carries
"System.Runtime.TieredCompilation.QuickJitForLoops": false. Or set it in the converted executable’s project
file, though the next conversion rewrites that file:
<TieredCompilationQuickJitForLoops>false</TieredCompilationQuickJitForLoops>
Converted executable projects carry this line, commented out. On linux-x64 (Canonical’s .NET 10, one 4-core
machine) it costs about 90 ms (16%) more startup time, and steady-state loop speed stays within measurement noise. It is
not the default, because no converted Go program is known to reproduce the fault.
Tuning converted code lists the runtime settings and
what each trades.
A Native AOT publish of a program that references the packages is slow and large
A program that references the go.* packages and publishes with Native AOT (PublishAot) runs. The check
that gates each release publishes a C# consumer of the packages and runs it on linux-x64, linux-arm64,
win-x64 and osx-arm64. On osx-x64 the publish is read when it finishes inside the hosted runner’s time limit, and reported as
not measured when it does not. A project that sets no trim mode of its own gets the packages’ default, partial,
which is the setting a converted project carries in its generated project file.
A full trim (TrimMode set to full) produces a program that runs as well. That was measured on win-x64 with
older packages and has not been re-measured since; the hosted check measures the default.
What it costs. With partial, Native AOT compiles every go.* assembly the program references in
full, not only the parts the program uses. With the published 1.26.11.1 packages, on a 4-core linux-x64 cloud
machine, the README walkthrough’s program, which uses github.com/fatih/color, took about 18 minutes to publish; the
executable is about 150 MB and runs in a fraction of a second. A converted project pays the same
cost, because it uses the same setting. Those packages leave the .NET SDK’s identical-method folding on, and that
pass takes most of the compiler’s time; the 1.26.11.2 packages turn it off for a Native AOT publish unless
the project sets IlcFoldIdenticalMethodBodies, which makes the publish several times faster and the executable
larger (Native AOT method body folding). They also write native debug
symbols, a symbol file of hundreds of megabytes beside the executable; the 1.26.11.2 packages leave those out
unless the project asks for them, which makes the publish a little faster
(Native AOT debug symbols).
With the 1.26.10.3 packages the walkthrough’s program does not publish at
all on linux-x64: the compiler stops at the native string table’s 2 GiB ceiling
(how to recognize it). A build, dotnet run and a publish without
Native AOT are not affected. For the 1.24.13.7 packages and earlier, see
Issues in older versions.
A Native AOT executable is larger because the standard library carries its async twins
The converted standard library is built with async twins: an async copy of each public function, and of the others
that can wait, which the experimental M:N scheduler runs (Async twins). A program that does not opt
in to M:N never calls them, but a Native AOT publish compiles them all the same. With the default trim mode,
partial, Native AOT compiles every member of every go.* assembly the program references
(the section above), twins
included. The executable is about 6% larger than the same publish without the twins, which is several MB for a small
program. A program that imports more packages, such as one that uses TLS, grows by more, in size and in share
(measured on win-x64, on the performance suite’s programs). The 1.26.11.1
packages carry no twins, so this begins with 1.26.11.2.
- A full trim does not avoid it. With
TrimModeset tofullthe twins are kept as well, and the executable is larger by about the same share. - A program that opts in to M:N carries the same twins. It references the same standard library, and it uses them.
- A program that runs on the JIT is not slower. The JIT compiles a twin only when something calls it, and in the performance suite no program on the JIT ran slower by more than the limit set for the change.
- Start-up can be a little slower. The suite’s start-up program, published with Native AOT, takes a few percent longer from launch to exit on one Windows machine. The larger image is the likely cause; that is not separately measured.
- One string benchmark is slower. Published with Native AOT, the suite’s string-view program runs about a quarter slower on the same machine, whether or not it opts in to M:N. Its loop is the same code with and without the twins; the larger image changes where that code is placed.
No setting leaves the twins out of a publish that references the go.* packages. A fix is planned as the next work
after 1.26.11.2: the twins move out of the class the packages’ extension host reads by reflection, and the go.*
assemblies become trimmable, so that a publish leaves out the standard-library code a program never calls.
The plan to close this gap is on the Roadmap.
Under Native AOT, converting a function to a Go-defined func type is slow
Symptom. A Native AOT executable whose code often converts a function to a func type that Go code declared with
type runs markedly slower with the go.* 1.26.11.2 packages than with earlier ones. A typical case is an AST
visitor passed to a walk on every node: go/ast’s Inspect, for one, converts the function it is given to its own
func type each time it is called. A program run under the JIT is not affected.
Cause. Since 1.26.11.2 a func type declared with type is a C# delegate of its own
(Every defined func type declares its own delegate).
A conversion to it builds the new delegate from the function’s target and method through reflection, which the JIT
makes cheap and Native AOT does not.
Workaround. Publish such a program without Native AOT: the converted project’s default dotnet publish
(ReadyToRun) runs the same code under the JIT. Where the Go code allows, convert the function once, outside the loop,
and reuse the converted value. The next release fixes it; it is tracked in
issue #43.
A single-file publish with composite ReadyToRun runs out of memory
A converted program’s project turns ReadyToRun on for dotnet publish. When the publish is also a single file
(-p:PublishSingleFile=true), the .NET SDK compiles ReadyToRun as a single composite image of the program and the
framework by default, and on that image the ReadyToRun compiler, crossgen2, expands golib’s nested generic types
until it runs out of memory: past 10 GB on a linux-x64 machine, failing with Insufficient memory and leaving
the build hanging. Compiled one assembly at a time, it does not. The publish profiles go2cs writes beside a
converted program (-p:PublishProfile=linux-x64 and the others) set
<PublishReadyToRunComposite>false</PublishReadyToRunComposite>, so a profile publish keeps ReadyToRun and is not
affected. A program converted by a go2cs earlier than 1.26.10.2 has profiles that turn ReadyToRun off instead,
since go2cs never overwrites a profile; replace their <PublishReadyToRun>false</PublishReadyToRun> with that
line to get ReadyToRun’s faster start back. A project converted by go2cs 1.26.10.3 or later carries the same line,
so a plain single-file publish is not affected either. A project converted by an earlier go2cs does not; on its command line,
turn the composite image off yourself:
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true -p:PublishReadyToRunComposite=false
A publish that is not a single file never makes a composite image, so it is not affected.
A conversion keeps a Go build cache of its own
When -stack-append is on, go2cs runs go build (and go test -c for test files) with -gcflags=-m for each
target the standard library ships, for each package it converts, so it emits the same stack-append buffers Go makes. The option is on by
default only for -stdlib and -tests; a plain or -recurse conversion runs none of these builds and never
creates the cache unless you pass -stack-append=on
(-stack-append). Those builds go into their own cache, not your GOCACHE:
go2cs/probe-cache under the user cache directory, or the directory named by -probe-cache or GO2CS_PROBE_CACHE.
The first conversion builds the standard library there for each target, about 60 MB each, and later conversions of
any module reuse it. Each converted package adds its own entries, which grow with the size of its compiled code: about 5 MB
for a goldmark package, and about 2.3 GB for one very large package. The separate cache moves this cost out of
your GOCACHE; it does not make it smaller. The first conversion of a large module needs that much free disk
once (a 97-package module needed about 12 GB), and later conversions reuse it.
Go removes entries unused for five days. To reclaim the space at once, delete the directory; the next conversion rebuilds what it needs:
rm -rf ~/.cache/go2cs/probe-cache
On Windows, the directory is %LocalAppData%\go2cs\probe-cache; on macOS, ~/Library/Caches/go2cs/probe-cache.
With no user cache directory (neither HOME nor XDG_CACHE_HOME set), the cache is go2cs-probe-cache-<uid> under
the temporary directory, created with mode 0700. Because that directory is shared, go2cs uses it only while it is a
directory owned by you that no other user can open; otherwise the run stops before its first probe and asks for
-probe-cache. A run that does not probe, such as -test-action build, never needs the directory.
The separate cache is new in go2cs 1.26.11.2. go2cs 1.26.11.1 runs the same builds in your own GOCACHE, so they take
the same space there, and it has neither -probe-cache nor GO2CS_PROBE_CACHE.
-stack-append is new in 1.26.11.2: go2cs 1.26.11.1 runs these builds for every conversion.
By default, cap() after appending to a slice that does not escape can differ from Go
Symptom. In a program converted without -stdlib or -tests, cap() of a slice built by append inside one
function can read lower than Go’s. Go 1.25 and later give the first append to an empty slice that does not escape a
32-byte buffer, so after var x []int64; x = append(x, 1) Go reads cap(x) as 4 where the converted program reads 1.
The slice’s contents and length are always the same; only its capacity, and code that reads the capacity, differ.
Cause. Reproducing the buffer needs the Go compiler’s escape decision for each append, which go2cs reads from a
go build -gcflags=-m per package and target. -stack-append controls it, and its default auto turns it on only for
-stdlib and -tests, where converted tests compare against Go’s own, because those builds cost time and disk (see
A conversion keeps a Go build cache of its own). The buffer is a
heap array in the converted program, so turning it on changes what a program can observe, not its speed or its
allocations.
Workaround. Convert with -stack-append=on (-stack-append) to reproduce
Go’s capacities. A single standard-library package converted without -stdlib takes the same default; convert it with
-stdlib <package> or -stack-append=on to get the standard library’s emission.
The default is new in go2cs 1.26.11.2. go2cs 1.26.11.1 emits the buffer for every conversion.
In optimized code, runtime.Caller can report an earlier line of the calling function
A function compiled with optimizations can lose the exact position of a call it makes. A runtime.Caller that reads
that function’s frame, from a function it calls, then reports the line of the function’s first statement instead of
the line of the call. Go always reports the call’s line. This is measured on linux-x64 and follows from how .NET’s
optimizing JIT records positions, so it is expected on every platform.
The loss needs a particular shape, measured here as a function that keeps runtime.Caller’s result in a variable
across a method chain written over several lines. Most functions report Go’s lines. Under the default runtime
settings a converted program reports the right line until the JIT recompiles the function with full optimization,
which happens after it has run many times. With DOTNET_TieredCompilation=0 it is compiled optimized from the start.
A Release build also gives every call in one statement the position of the statement. Two calls to the same function
in one statement, such as a method chain written over several lines (b.On(1). then On(2) on the next line), then
both report the line of the first call. This holds under every JIT setting, because the positions a frame can report
are fixed when the assembly is compiled.
Converted Go tests are not affected. The test assembly go2cs writes for a package’s tests is
compiled without optimization, so t.Logf, testify’s failure locations and every other line read from test code match
Go, while the package under test stays optimized. To build a test assembly optimized, for a benchmark run, set the
MSBuild property GoTestOptimize to true (-p:GoTestOptimize=true). go2cs 1.26.11.1 compiles test assemblies
optimized and has no GoTestOptimize, so lines read from test code can show the same loss there.
To get Go’s lines in a program, use one of these, at a large cost in speed:
- a
Debugbuild, which reports both cases as Go does: in the measurement above, about 38 times slower than the defaultReleasebuild on acrypto/sha256workload; DOTNET_JITMinOpts=1in the program’s environment, which keeps aReleasebuild but turns off JIT optimization: it reports the call’s line instead of the function’s first statement, but not two calls of one function in one statement apart; about 33 times slower on the same workload.
Under Native AOT, runtime.Caller reports line 0 instead of the call’s line, measured on linux-x64; the function
name it reports matches Go. Neither route above applies to a Native AOT program, so for Go’s lines run the program
under the JIT with one of them.
Inside a range-over-func loop kept as a foreach, runtime.Caller names the enclosing function
Symptom. Inside the body of a for … range loop over an iterator function that converts to a foreach, such as
a loop with a defer in its body, runtime.Caller and runtime.FuncForPC report the function that holds the loop,
for example main.f. Go reports the loop body’s own name, main.f-range1.
Cause. go2cs converts most of these loops to a call of the iterator, with the loop body as a function that takes
Go’s name, so runtime.Caller inside it reports what Go reports. A loop with a defer in its body, a body that can
block, or one of the other forms the
Reference
lists, keeps the foreach form, and its body runs in the enclosing function’s own frame. The loop bodies that do take
a name are numbered as Go numbers them, kept loops included, so only the kept body’s own frame differs.
Workaround. None that keeps the program’s behavior: moving the body into a function of its own changes when its
defer runs. Code that reads frame names sees the enclosing function’s name for such a body.
In go2cs 1.26.11.2, only the kept loops differ. In go2cs 1.26.11.1 every range-over-func loop takes the foreach
form, so every loop body reports the enclosing function.
In a few statement forms, a variable read beside a call can see its value from before the call
Symptom. A statement reads a variable and also calls a function that changes that variable, and the converted
program prints the value from before the call where Go prints the value from after it. For example, with a
package variable g and a function bump that adds one to g, a package-level var x = pick(g, bump()) passes
pick the old g in the converted program and the new one under Go.
Cause. Go’s specification fixes the order of the calls in a statement but not when the statement’s other operands are read against them. Go’s compiler runs every call of the statement first and reads the other operands after, and C# reads every operand left to right. go2cs moves a statement’s calls ahead of it where a call can change something an earlier operand reads, so most statements match Go (Multi-Assignment and Evaluation Order). These forms keep C#’s left-to-right order:
- a
caseexpression of aswitch(the switch’s own tag is covered); - a package-level variable’s initializer;
- any other statement whose calls the converter cannot fully order: such a statement keeps C#’s left-to-right order as a whole, and none of its calls moves.
A division that panics is a related case. In fmt.Println(x/y, bump()) with y zero, Go runs bump and then panics
on the division; the converted program panics first, so bump never runs.
Workaround. Make the call its own statement first, then read the variable: b := bump() and then
x := pick(g, b) reads g after the call in both languages.
Two goroutines writing one map are not always caught
Symptom. A program writes one map from two goroutines without a lock. Go usually stops it with fatal error:
concurrent map writes and exit status 2. The converted program prints the same report and exits 2 most of the
time, but a race can also go unnoticed: the program finishes, and the map can be left missing entries or with a
damaged table. Now and then the damaged table fails first, and the program prints .NET’s
System.IndexOutOfRangeException report instead of Go’s text (still exit 2). A goroutine reading a map while another writes it is reported the same way, as Go’s fatal error:
concurrent map read and map write, when the read notices it and its frame is still in the trace; with every
frame inlined, it reads as two writers do.
Cause. A Go map is a .NET Dictionary in the converted program, and golib reports Go’s text when Dictionary
notices the race, or when the table the race damaged fails on its next resize. Go checks a flag on every map write.
That flag catches the race every time in our measurements, but it costs up to 5 percent on a map store under Native
AOT, so go2cs does not carry it. Go’s own check is best effort too: it notices a race when it sees one, and does not
promise to see every one. Eight goroutines writing one map a million times each are reported in every run of a
program built for the JIT, and in none of a Native AOT build of the same program, which finishes with the map
damaged.
Workaround. Guard a map that more than one goroutine writes with a sync.Mutex, or use sync.Map, as Go
requires. To look for such races, run the Go program under go run -race.
A var declaration of two names from one value does not order its operand
Symptom. A var statement declares two names from one two-value expression, such as a map index, a type
assertion or a channel receive with its ok. Two things go wrong in the operand:
- A call whose several results pass straight into another call does not compile:
var y, ok = m[f(g())], with agthat returns two values, fails with CS7036. - A method value is not copied when the statement runs, so calling it later sees later writes to its receiver:
after
var f1, ok1 = any(c.Get).(func() int)andc.Inc(),f1()returns the incremented value in the converted program and the old one under Go. Nothing reports it.
Cause. go2cs moves a statement’s calls and copies ahead of it where Go’s order needs them
(Multi-Assignment and Evaluation Order).
For a var declaration it does this only when the names and values pair one to one, so a two-name, one-value
declaration keeps its operand as it is. The same statement written with := is ordered.
Workaround. Write the declaration with :=: y, ok := m[f(g())] and f1, ok1 := any(c.Get).(func() int)
convert as Go runs them. A package-level var has no such form; give its operand a variable of its own first.
A local from a function of a self-referential func type reports the named type
Symptom. A := local takes a function or method value whose signature leads back to a package func type, as
st := lexStart does beside type stateFn func(*lexer) stateFn, or pp := pingStart beside type ping func(*lexer)
pong and type pong func(*lexer) ping. Go gives the local the unnamed func type. The converted program gives it the
named one, so once the local is put in an interface it reports the wrong type: fmt.Printf("%T", st) prints
main.stateFn where Go prints func(*main.lexer) main.stateFn, and switch any(st).(type) takes the case stateFn
arm where Go takes case func(*lexer) stateFn. Nothing reports it.
Cause. go2cs declares such a := local with the named delegate so that a reassignment from a call through it
(st = st(l), which yields stateFn) needs no conversion. C# can write the unnamed type: an explicitly typed local
is declared Func<ж<lexer>, stateFn> and each reassignment is converted, and that program reports Go’s type. Any
other := signature gets the unnamed type, as Go gives it
(Value-Receiver Delegates).
Workaround. Declare the local with its type written out: var st func(*lexer) stateFn = lexStart, or
var pp func(*lexer) pong = pingStart. Calls through the local and reassignments into it behave as in Go either
way; only the := local’s dynamic type differs, so the symptom needs the local itself in an interface.
A call whose results spread into another call can run before a call written to its left
Symptom. A statement passes a call’s several results straight into another call, as f(g()) does with a g that
returns two values, and the first such spread sits in the left operand of an && or || whose right operand calls,
with a later spread after it. The converted program runs the first spread before a call written to its left:
return h() == f(g()) && ok(), f(g2()) runs h, g, f, ok, g2, f under Go and g first in the converted
program.
Cause. C# has no way to pass one call’s results as several arguments, so go2cs evaluates g() into temporaries
ahead of the statement, and moves the calls Go runs before it ahead of it too
(Multi-Assignment and Evaluation Order).
Here, moving the calls before the first spread would also move the &&’s right operand ahead of the later spread on
its own, which must not run unless the left operand lets it, so the statement keeps C#’s order.
Workaround. Make the && its own statement first: v := h() == f(g()) && ok() and then return v, f(g2()).
A method value in the index of x++ or x-- sees later writes to its receiver
Symptom. An increment or decrement statement’s index saves a method value whose receiver is a value, and a later
statement changes that receiver. The saved func value reads the later value in the converted program and the value at
the statement under Go. For example, xs[store(o.Get)]++ followed by o.n = 9: a later call of the saved func value
returns 9 in the converted program and the earlier value under Go.
Cause. go2cs copies a value receiver where Go evaluates the method value, in a declaration ahead of the statement
(Every receiver a later write could reach is copied at binding).
An increment or decrement statement has no place for that declaration yet, so the func value reads the variable
itself. An assignment, including xs[store(o.Get)] += 1, copies as it should.
Workaround. Evaluate the index as its own statement first: i := store(o.Get) and then xs[i]++.
A func literal called in a type switch guard loses its writes to a captured variable
Symptom. A type switch’s guard calls a func literal that assigns a variable of the enclosing function, as in
switch v := func() any { i = 2; return C{i} }().(type). After the switch starts, the converted program still sees
the old value of i: printing v.n, i in the case prints 2 1 where Go prints 2 2.
Cause. go2cs emits the assignment inside the func literal as a new declaration (nint i = 2;), so the write goes
to a local of the lambda instead of the captured variable. A func literal outside a type switch guard converts as it
should.
Workaround. Call the func literal in its own statement first: x := func() any { i = 2; return C{i} }() and then
switch v := x.(type).
Package initialization outside the standard library: the limits
A package outside the standard library initializes as Go does: package main’s entry point
initializes every package of the program in Go’s order before main
(Package-Level Variable Initialization Order).
go2cs 1.26.11.1 initializes such a package when .NET first touches it. These limits remain.
A package variable whose initializer starts a goroutine indirectly, and waits for it, hangs.
Symptom. var ready = start(), where start reaches a goroutine only in one of the ways listed under Cause, and
that goroutine reads another variable of the package while start waits for its answer, never returns.
Cause. The converter moves an initializer out of the class’s type initializer when it, or a function of the
package it calls directly, holds a go statement, hands a function to a package outside the standard library, or
hands one to a standard-library function that runs it on a goroutine (sync.WaitGroup.Go, time.AfterFunc,
context.AfterFunc, iter.Pull, and a few more). It does not move an initializer that reaches the goroutine only
through one of these:
- a call through an interface method, or through a function variable;
- a function handed to the other package inside another value: a struct field (
runner.Task{F: two}), or a slice of functions ([]func() int{two}); - a value of the package whose method the other package’s goroutine calls (
runner.RunJob(job{})); - a function that a call returns, called at once (
runner.Starter()(two)).
An initializer it does not move runs as a C# static field initializer,
inside the type initializer, and a second thread that reads a static field of the class waits until the type
initializer finishes. A goroutine that reads only its own arguments is not affected. Workaround. Do the work in an
init function (var ready bool and func init() { ready = start() }): init functions run outside the type
initializer. Or pass the goroutine the values it needs as arguments.
Without a converted Go program, packages initialize in .NET’s order.
Symptom. In a library used from C#, in a converted program run from a host other than its own entry point (a C#
host, or the test host of a package main), and in the host that runs a package’s converted tests (-tests), an imported
package still initializes before its importer, but two packages that do not import each other initialize in the
order .NET loads them, where Go sorts them by import path. An init function, or a package variable’s
initializer, that starts a goroutine which calls the package and waits for it hangs there. Cause. With no Go
main, each package runs its initialization from its
own module initializer, and a module initializer holds a lock that the goroutine waits on. Workaround. Do not
depend on the order of two packages that do not import each other; import the one that must come first. Start such
a goroutine on first use rather than from init.
A dependency converted by an older go2cs initializes earlier than Go.
Symptom. A package converted by go2cs 1.26.11.1 or earlier, referenced by a program converted by 1.26.11.2, runs its
init functions when the program’s module initializers force it, before the program’s other packages and so
before Go would. Cause. Such a package has no ᴛᴛinit for the program to call, so the program falls back to
forcing its module, as before. Workaround. Convert the dependency again with the same go2cs as the program.
In a converted test package, a test file’s relocated initializers run after the package’s init functions.
Symptom. A package variable declared in a _test.go file, whose initializer reads a variable declared later or in
another file, is assigned only after the package’s own init functions have run; Go assigns it before them. An
init function in a production file that reads such a test variable sees its zero value. Cause. The test files
compile into the test assembly, which runs their relocated initializers from its own module initializer after the
production package’s initialization. Workaround. Have the init function read the variable through a function
called later, or declare the variable in the file that reads it.
Another package’s unexported interface method, met through an embedded struct, is refused
Symptom. Converting a package stops with error GO2CS2016 at a conversion such as lib.CallM(u) or
var j J = U{}, where U embeds a struct from another package (type U struct{ lib.T }), the interface declares
an unexported method of that package (lib.I with m()), and either U declares a method m of its own or m
returns a value. A type argument checked against such an interface (lib.F(u) with func F[X I](x X)) is refused
the same way.
Cause. Go names an unexported method by its package, so U can hold two methods m: lib.T’s, promoted, and one
U declares itself. lib.I is met by lib.T’s. A converted interface adapter maps a method by its name alone, so it
would call U’s own m (the program would print main.m where Go prints lib.m). Without one it cannot call
lib.T’s, which is internal to lib’s assembly, so it stands in a method that does nothing and returns a zero value.
go2cs refuses the conversion where that would be wrong: a rival m, or an m that returns a value. It cannot be
downgraded with -warn. Promotion through an embedded interface field (type U struct{ lib.I }) converts and calls
the right method, unless the path to that field crosses an unexported field of another package (type T struct{ impl }
in lib), which is refused; any interface whose methods are all exported converts too.
An unexported method that returns nothing, with no method of that name on U, is not refused, because the stand-in
does what such a method usually does: nothing. That is the sealed-marker idiom of generated gRPC code
(type server struct{ pb.UnimplementedGreeterServer }, whose mustEmbedUnimplementedGreeterServer() is empty), and
it converts and runs as in Go. If the marker’s Go body does have an effect, the converted program skips it silently.
Workaround. Pass the embedded value itself (lib.CallM(u.T)).
The same mix-up reaches a type assertion, which the refusal cannot see because it is decided when the program runs:
a value that meets another package’s unexported method only through an embedded struct reads false where Go reads
true. net.Buffers.WriteTo’s w.(buffersWriter) is one: for a type that embeds *net.TCPConn, Go uses the
connection’s vectored write and the converted program takes the plain write loop. The bytes written are the same.
The refusal is new in go2cs 1.26.11.2. go2cs 1.26.11.1 converts the conversion and calls the wrong method, or fails to build with CS1929.
A few generic shapes declared inside a function do not build
Symptom. The converted package fails to build (CS0246, CS0102, CS1503 or CS0029) at one of these Go shapes:
- a generic type declared inside a function and instantiated there:
func run[T any](v T) { type L[K any] struct{ K K }; l := L[T]{v} }; - a local alias of an anonymous struct over the function’s type parameters:
type pair = struct{ K K; V V }insidefunc f[K comparable, V any]; - a local type whose field is named like a type parameter it reaches only through another local type:
type inner struct{ x K }; type outer struct{ K int; in inner }insidefunc f[K comparable]; - two generic functions that return the same anonymous struct with their type parameters in a different
order:
func ga[K comparable, V any]andfunc gb[V any, K comparable], both returning[]struct{ K K; V V }; - a value of an anonymous struct returned by a generic function passed where the same struct is spelled with
concrete types:
plain(r[0])withr := pairs("a", 1)andfunc plain(e struct{ Key string; Val int }).
Cause. go2cs gives an anonymous or local type in a generic function a C# name of its own with the function’s
type parameters (pairs_R0<K, V>). Go treats the struct as one type whatever its spelling; in C# the lifted
type and the same struct written with concrete types are two types, and a local alias cannot carry type
parameters at all. The first and fourth shapes name the lift by the wrong spelling or parameter order.
Workaround. Declare the type at package level, as a named generic type (type pair[K comparable, V any]
struct{ K K; V V }), and use it in every place the anonymous struct appeared.
Each shape fails at build time; none builds and then runs differently.
The zero value of a type parameter whose type argument is an array
Symptom. A program panics with go2cs: the zero value of a type parameter whose type argument is an array has no
length in C#, where Go runs. Or a conversion prints warning GO2CS2019 at a generic struct used with an array type
argument, such as var c Cell[[2]int] with type Cell[T any] struct{ V T }, and the converted program then reads
len(c.V) as 0 where Go reads 2.
Cause. C# spells every Go [N]E as the one array<E>, so the length of an unnamed array is held in the array
value and not in its type. A zero value built from the type alone has no length to build from. go2cs carries the
length into an unexported generic function (see
the array-dims companion),
and nowhere else:
- In a method of a generic type, the zero value of a type parameter (
var z T, a named result, blank or not,new(T), a map miss that returns a value), or of a struct that holds one by value (var c Cell[T], a miss ofmap[K]Cell[T]), panics with the message above when the type argument is an unnamed array. It is right for every other type argument. A comma-ok map read whose value a miss never shows (_, ok := m[k];if v, ok := m[k]; ok { ... }, orok && ..., that does not readvin anelse;if v, ok := m[k]; !ok || ... { ... }that does not readvin its body, asmaps.Equalandmaps.EqualFuncdo) does not panic. Nor does anew(T)that the next statement overwrites (p := new(T); *p = v), which builds no zero at all. Any other zero panics where it is declared, even when Go never shows it: a stack’svar zero Treturned only when the stack is empty panics on a non-emptyPoptoo, and named results that a map hit overwrites (func (c *Cache[K, V]) Get(k K) (v V, ok bool) { v, ok = c.m[k]; return }) panic on the hit. Refusing only where the zero is read would put a test on every length read of every array, sized ones included. In the standard library,iter.Pullanditer.Pull2with an array element type panic when called: their state holds a zero of the element, and the closingnext()returns it.ArrayTypeArgZeroRefusalspins both. - Outside generic code, there is no type parameter left to test when the program runs, so the conversion warns
instead:
GO2CS2019at each instantiation of a generic struct that holds its type parameter by value with an unnamed array type argument. The zero value of that struct (avar,new,make, a map miss, or a literal that leaves the field out) holds a length-0 array.
A named array type (type A2 [2]int) converts to a type that knows its length, and is not affected by either.
These forms are not covered yet and build a length-0 array silently: a channel receive from a closed channel, a failed
type assertion, a composite literal that leaves a type-parameter field out, the elements of make([]T, n), and the
elements of an array of a type parameter (var a [2]T), in generic code; and the zero value of a generic struct that
holds both its type parameter and an array field of its own. A slice or an array whose elements are all assigned before
they are read is right. ArrayTypeArgZeroRefusals pins the two element forms: each element of make([]T, n) and of
[2]T has length 0 there, where Go’s has 2.
A [0]E type argument panics too, where Go’s zero value (an empty array) would be right. It cannot be told from
any other length when the program runs: Table[string, [0]int] and Table[string, [2]int] are one C# type,
Table<@string, array<nint>>, so a method sees the same type argument for both. Use a named type
(type Empty [0]int) or a slice.
Workaround. Use a pointer or a slice type argument (Cell[*[2]int], Cell[[]int]). A named array type argument
(Cell[A2]) also gives the right zero value. Giving the field a value (Cell[[2]int]{V: [2]int{}}) is right too,
but the conversion still warns at that site, and a map miss has no field to set.
A copy of such a struct value (m["k"] = x, y := m["k"]), with an unnamed or a named array type argument, does
not build: CS1061, ΔClone is not defined on Cell<array<nint>>. A pointer or a slice type argument builds.
The panic and the warning are new in go2cs 1.26.11.2. go2cs 1.26.11.1 builds the length-0 array silently, so a zero that is never shown, as in the stack and the cache above, ran there and panics now.
A constraint with a method and a type term does not compile
Symptom. A converted package fails to build (CS0305, CS0246, CS0535 in generated files) when a generic function
or type is constrained by an interface that lists both a method and a non-pointer type term, such as
interface{ ~string; String() string } or interface{ ~int; String() string }, and is instantiated with a defined
type that has the method (type Mode string with func (m Mode) String() string).
Cause. go2cs turns such a constraint into a generic C# interface that takes the type argument as a parameter. The
record that says Mode implements it, and the implementation go2cs-gen generates from that record, are written
without that parameter, so neither compiles. A constraint with a method and no type term, or a type term and no
method, converts and runs as in Go.
Fixed in go2cs 1.26.11.2: the record names the interface with its type argument, in the named and the inline spelling, and a constraint generic itself (a method naming the type parameter) is named without a second type argument, recorded per type argument and checked with its term’s operators; a string, string-or-bytes, slice or map term keeps the surface it has without methods beside the method interface; and go2cs-gen writes no pointer proxy for such a constraint, so both examples above convert, compile and run as in Go. go2cs 1.26.11.1 still has the issue; with that release, use the workaround below.
Workaround. Keep the type term in the constraint and pass the method as a function value:
func show[T ~string](t T, str func(T) string), called as show(m, Mode.String). Or constrain on the method alone
(fmt.Stringer) where the body does not need the type term.
Still open, for a constraint with a type term (with or without a method):
- An alias of the constraint (
type S2 = Stringer,type N2 = Number) used as a constraint ([T S2]) converts towhere T : S2overglobal using S2 = …Stringer;, which names the generic interface without its type argument, and the converter warns thatS2is not an interface. The package does not compile. Use the constraint’s own name in the type parameter list. - A type parameter passed from one generic function to another, when both spell the same inline constraint and its
method names another type parameter (
[K comparable, T interface{ ~[2]int; Key() K }]on both, the outer one callinginner[K](v)), does not compile (CS0314): each function’s constraint becomes its own interface, and the outer function’sTdoes not satisfy the inner one’s. The constraint may have no type term at all ([K comparable, T interface{ Key() K }]) and fails the same way. In either spelling, take the method as a function value rather than naming it in the constraint:func inner[K comparable, T ~[2]int](v T, key func(T) K) K, orT anywhere there is no type term, called asinner(v, Pair.Key). - A named generic constraint given another type parameter nested inside a type (
[K any, T into[[]K]], called asnested(Many{2}, []int{1})) does not compile (CS0315), with or without a type term: the constraint is closed over the instantiation only where its argument is the other type parameter itself (into[K]), so no record saysManyimplementsinto<slice<nint>>. Take the method as a function value, as above, or give the constraint the bare parameter (into[K]withKthe slice type). - A pointer type argument under a constraint naming another type parameter (
func ptr[K any, T into[K]](v T, k K) K, called asptr(&Box{7}, 1)with a pointer-receiverInto) does not compile (CS0311): the call passesж<Box>againstwhere T : into<K>, and neither the record nor the pointer proxy a constraint naming only its own type parameter gets is written for it. Pass the method as a function value, or instantiate with a value-receiver type.
A select or a conversion to a plain channel on a channel type parameter does not compile
Symptom. A converted package fails to build (CS1061, CS0411, CS0030) when a generic function whose type parameter
has a channel core ([C ~chan E], or a named constraint over one) uses a value of it in a select case, or converts
it to the plain channel type ((chan E)(c)).
Cause. go2cs constrains such a parameter to IChannel<E>, which declares the typed send and receive, close and
ranging, and these convert and run as in Go, as does comparing the value with nil. A select case needs the
channel’s select forms, which IChannel<E> does not declare, and C# has no conversion from a type parameter to the
plain channel type. Converting to the parameter’s own type (C(c)) converts.
Workaround. Convert to the plain channel type at the call site, where the type is concrete, and pass the plain
channel (chan E) to the code that selects on it.
Under the experimental M:N scheduler (GO2CS_MN=1), a send or receive through such a type parameter does not park:
it is a plain call, and the goroutine keeps its thread until it returns, as a plain standard-library call does
(Async twins).
A constant meeting a complex type parameter is not converted
Symptom. In a generic function whose type parameter admits a complex type ([T ~complex64 | ~complex128], or a
constraint built from one), comparing a value with a constant (v == 1, v != 0, or a switch v with a constant
case), or declaring a variable of the parameter with a constant (var o T = 1), stops the conversion with error
GO2CS2018, naming each site. Arithmetic with a constant (v*2 + 1), a conversion of a constant (T(1)), and a
constant returned or assigned (return 1, v = 3) convert and then do not compile.
Cause. Go types an untyped constant that meets T as T. go2cs turns that into a call that builds the value for
the instantiation, and it has that call for integer and floating-point sets only. For a complex set the constant
would stay a plain number: arithmetic finds no operator, and a comparison, or a variable holding the number, would
answer false where Go answers true, so go2cs refuses those rather than convert them wrong.
Workaround. Pass the constant in as a T from a call site whose type is concrete
(isOne(v, complex(1, 0))), or write the function for the concrete complex type.
Bool operations on a bool type parameter do not compile
Symptom. A converted package fails to build (CS0023, CS0019, CS0029, CS0030) when a generic function whose type
parameter is constrained to bool or a defined bool type ([T ~bool]) uses a value of it as a bool: !a, a && b,
a || b, a condition (if a), a constant (return true), or a conversion (bool(a), T(b)).
Cause. go2cs writes each of these as it stands. C# has no logical operator, condition or conversion on a type
parameter, and no .NET interface states one that a constraint could name. == and != on the same parameter convert
and run as in Go.
Workaround. Write the bool logic on the concrete type and pass it in as a function value
(func not[T ~bool](a T, neg func(T) T) T), or write the function for the concrete type.
In generic code, x /= b on a target whose index is a call can divide complex values by .NET’s rule
Symptom. In a generic function whose type parameter allows complex128, xs[next()] /= b divides by .NET’s
rule for complex numbers, so a zero divisor gives (NaN+NaNi) where Go gives (+Inf+NaNi) for (1+0i)/0. A finite,
non-zero divisor gives the same value in both.
Cause. go2cs divides complex128 values with a port of Go’s runtime division
(A complex128 division calls golib’s quo).
For x /= b on a type parameter it writes x = quo(x, b) where x can be read twice without repeating a call, a
map element included. Any other target keeps C#’s /=, which takes .NET’s operator. This is new in 1.26.11.2; in
1.26.11.1 every complex128 division takes .NET’s operator.
Workaround. Read the index once: k := next() and then xs[k] /= b.
A float32 constant written with a shift can round differently from Go
Symptom. A float32 constant expression of literals that includes a shift prints a slightly different value:
var s1 float32 = 0.1 * (1 << 3) * 0.3 prints 0.24000001 where Go prints 0.24, and
float32(1 + 1.0/(1<<24) + 1.0/(1<<60)) prints 1 where Go prints 1.0000001.
Cause. Go evaluates a constant expression exactly and rounds the result to float32 once. go2cs folds literal
constant arithmetic to that value where its operators are +, -, * and /
(Constant Values); an operand written as a shift leaves the
expression as written, and C# computes it in float32, rounding at each step. The same expression without the shift
(0.1 * 8 * 0.3) folds and prints 0.24.
Workaround. Write the shifted operand as its value (8 for 1 << 3).
Two packages’ same-named types, converted to one interface, do not build
Symptom. A package converts a value of one package’s type and of another’s, both with the same package name and
type name (a/util.Kind and b/util.Kind), to one interface of its own, and the converted project fails to build
with CS0102: the type already contains a definition for util_KindᴠShower.
Cause. The C# adapter that lets a value type meet an interface is named from the type’s package name, its type name and the interface name, so the two types get one adapter name.
Workaround. Convert one of the two through a type of the converting package that forwards the methods the
interface needs: type bKind util.Kind, func (k bKind) Show() string { return util.Kind(k).Show() }, and
return bKind(2). An import alias does not change the adapter’s name, which comes from the package name.
A loop condition that reads a struct loop variable inside a function literal does not compile
Symptom. Building the converted program fails with error CS0841 (a local variable used before it is declared)
at a three-clause for loop whose variable is a struct and whose condition reads that variable inside a function
literal, such as for t := (T{0}); ok(func() int { return t.n }, 30); t.n += 10 { ... }.
Cause. The converter writes the literal’s copy of the variable (var tʗ1 = t;) ahead of the loop, before the
line that declares t. A loop variable of a basic type such as int in the same place converts and runs as in Go.
Workaround. Move the test into the loop’s body, where the literal reads the variable as Go does:
for t := (T{0}); ; t.n += 10 { if !ok(func() int { return t.n }, 30) { break }; ... }.
Four uses of the pointer-method constraint idiom are refused
The idiom func F[T any, PT interface{ *T; M() }], in its inline spelling or through a named constraint such as
type Setter[T any] interface{ *T; Set(string) }, converts and runs as in Go: PT becomes ж<T> and its methods
are called through a shape witness (see
the reference).
That is go2cs 1.26.11.2; go2cs 1.26.11.1 has no shape witness and does not convert the idiom to working C#.
Four uses are refused by name with GO2CS2013, and the package is not converted:
- a method value taken through
PT:f := p.Set; - a
PTconverted to a non-empty interface:var s fmt.Stringer = p, in a function its own package instantiates with a pointer (one its package never instantiates, such asinspector.Allin golang.org/x/tools, converts it); - a type argument whose pointer is not to a non-generic named type of the package being converted:
F[Pair[int]], orF[other.T]; PTpassed on to a generic function whose constraint is neitherPT’s own constraint nor one that constraint embeds: from[T any, PT SetGetter[T]]to[T any, PT Setter[T]], whereSetGetterlistsSetwithout embeddingSetter.
A function its own package never instantiates with a pointer, one written only for its importers, is also refused
(GO2CS2013) wherever it calls a method through PT, because no witness is emitted for it;
instantiating it in its own package over one of that package’s non-generic named types makes it convert for calls
from that package, while a call from another package is still refused. Converting PT to the interface and calling
the method on the interface value converts there: var q Positioner = p; q.Pos().
Workaround: call the method through a func literal, f := func(s string) { p.Set(s) }; convert a concrete
pointer rather than PT, inside a function that names the type; or instantiate over a non-generic named type of the
package that declares the method itself; or make the wider constraint embed the narrower one
(type SetGetter[T any] interface{ Setter[T]; Get() string }); or declare a generic written for its importers in the
package that instantiates it.
A package that instantiates another package’s generic at its own pointer type through a generic named pointer-method
constraint, as a caller of zap’s ObjectValues[T any, P ObjectMarshalerPtr[T]] does, is refused with
GO2CS2005; spelling the constraint inline in the declaring package
(P interface{ *T; ObjectMarshaler }) converts where the generic only hands P on to a generic type, as
ObjectValues does.
A pointer type argument’s zero value, or an explicit pointer instantiation, through a method constraint
Symptom. Two shapes of a generic function whose type parameter is constrained by methods and instantiated with a pointer type:
- The zero value of the type parameter, converted to an interface, compares equal to
nilin the converted program. Withfunc zero[T both]() namer { var z T; return z }called withT=*P, Go returns a non-nil interface holding(*P)(nil), andzero[*P]() == nilis false; the converted program answers true, and calling a method on the result panics with a nil dereference where Go calls the method on a nil*P. - An explicit pointer instantiation with no value argument of that type,
zero[*P](), does not build (CS0311). Cause. A pointer type argument is passed as a constraint proxy, a generated class that wraps the pointer and implements the constraint (generic constraints). The zero value of that class is a null reference rather than a proxy over a nil pointer, so it loses the type*P. The proxy is chosen only where the type parameter is itself a parameter or result of the function, sozero[*P]()passes the pointer type unwrapped, which does not satisfy the C# constraint. Workaround. Return or convert a value the caller supplies (func pick[T both](v T) namer { return v }keeps the type), and give an explicit pointer instantiation a parameter of the type parameter’s type.
On Windows, time.LoadLocation finds no time zone unless the program brings the zone data
Symptom. On Windows, time.LoadLocation("Europe/Berlin") returns the error
unknown time zone Europe/Berlin, where the same Go program, built on a machine with Go installed, finds the zone.
Cause. Windows has no system time-zone database. Go looks for the zone in the file ZONEINFO names, then in
lib/time/zoneinfo.zip under runtime.GOROOT(), then in the data time/tzdata embeds. In a Go binary,
runtime.GOROOT() falls back to the Go installation the binary was built with, which Go’s linker records. In a
converted program it falls back to nothing, so the zone file is found only when GOROOT is set in the environment.
On a machine without Go, a Go program fails the same way.
Workaround. Do one of these:
- Import
time/tzdata(import _ "time/tzdata"), which embeds the zone data in the program. This is Go’s own answer for a machine without Go. - Set
ZONEINFOto azoneinfo.zip, such as the one inlib/timeof a Go installation. - Set
GOROOTto a Go installation.
Linux and macOS read the system’s zone files, as Go does, and are not affected.
Issues in older versions
These issues are fixed in go2cs 1.26.11.2 or earlier and affect only the releases each entry names.
With the go.* 1.26.11.1 packages or earlier, on Apple silicon the standard library is the amd64 build
The go.* packages through 1.26.11.1 ship the darwin/amd64 standard library in their osx-arm64 assets, the
same build their osx-x64 assets carry. On an Apple-silicon Mac a converted program runs as a native arm64 .NET
process, and runtime.GOARCH reads arm64, as Go’s own program on the same Mac does, but everything Go decides by
architecture at build time follows amd64: Go’s _arm64.go files are not in the packages, internal/goarch
reports amd64, and a constant Go computes from the architecture keeps its amd64 value.
Fixed in the go.* 1.26.11.2 packages: their osx-arm64 assets are the darwin/arm64 build, so on Apple silicon
internal/goarch reports arm64 and Go’s _arm64.go files are in the packages, as in Go. Take every go.* package
from 1.26.11.2 or later; go2cs’s build check stops a build that mixes them.
Workaround with the 1.26.11.1 packages: rely on runtime.GOARCH for the machine’s architecture, never on the
presence of an architecture-specific path in the standard library.
With go2cs 1.26.11.1 or earlier, a -recurse=nuget conversion reads an older local go2cs root and emits names the packages do not have
Symptom. A program converted with go2cs -recurse=nuget does not build against the published go.* packages,
with CS0426 on a standard-library name that carries a Δ prefix the packages no longer have, for example
reflect_package.ΔKind. The conversion itself reports no warning and exits 0. The names affected are the
standard-library names that earlier go2cs releases prefixed with Δ and the published packages no longer do, about
170 across about 70 packages, among them time.Second, time.Month, reflect.Type, reflect.Value and
os.Signal, so most programs converted on such a machine meet it.
Fixed in go2cs 1.26.11.2: under -recurse=nuget the converter reads standard-library names only from the
metadata built into it, and says once when it finds a local go2cs standard library that it does not read. go2cs
1.26.11.1 and earlier have the issue; with them, use the workaround below.
Cause. Under -recurse=nuget the converter still looks for a local go2cs root: -go2cspath when it is given,
else the GO2CSPATH environment variable, else ~/go2cs (%USERPROFILE%\go2cs on Windows). When that folder holds
a go2cs standard library, the converter reads each imported package’s names from it, ahead of the metadata built
into the converter, which is the metadata that matches the published packages. A root from an older go2cs release,
such as one left by an earlier deploy-core or a go2cs clone, supplies that release’s names. On a machine with no
such folder and GO2CSPATH unset, the emission is correct.
Workaround with go2cs 1.26.11.1 and earlier. Make the run unable to find an old root: unset GO2CSPATH and pass -go2cspath an empty folder, or
move the old ~/go2cs aside for the run. Then convert again. Measured on windows-amd64 and linux-x64.
With the go.* 1.26.11.1 packages or earlier, under Native AOT a type assertion to error that the method set decides can answer false
Symptom. In a Native AOT executable (PublishAot), a Go type assertion to error answers ok == false for a value
whose method set has Error() string when no compile-time adapter for that pair exists. Measured with
var p any = new(runtime.PanicNilError); _, ok := p.(error): Go and the JIT answer true, Native AOT answers false.
No exception is raised, so the program goes on with the wrong answer. A failing assertion still answers correctly.
Fixed in the go.* 1.26.11.2 packages: error declares a second run-time shell that holds the value without a generic
type closed over it, so Native AOT has code for it and the assertion answers as Go’s does. The go.* 1.26.11.1
packages and earlier have the issue; with them, use the workaround below.
Cause. The runtime library finds the method (its method-set check answers true), then builds the interface value
from error’s run-time shell, error<T>, closed over the value’s type with MakeGenericType. Native AOT has no code
for that instantiation, and error declared no second shell that needs none, so the assertion read as a miss.
Inferred from the code, not measured: interfaces the converter generates declare that second shell, so this reaches
error and not them.
Workaround with the go.* 1.26.11.1 packages. Publish without Native AOT: the converted project’s default
dotnet publish (ReadyToRun) and a framework-dependent build run the same code under the JIT, which answers as Go
does.
With go2cs 1.26.11.1 or earlier, an untyped constant shifted into a named integer type wraps its count
Symptom. A shift of an untyped constant by a count that is not constant, where the context gives the shift a
named integer type (m & (1 << uint(32-1-i)) with m an fs.FileMode, or var c U32 = 1 << s), wraps its count at
the type’s width. A count of the width or more gives the wrapped value where Go gives 0 (or -1, for a negative value
shifted right), and a negative count does not panic. A computed constant over untyped named constants in that
context, such as (bias + 1) << s, does not compile (CS0019).
Cause. The converter wrote the constant as the named type’s underlying integer type and shifted it with C#’s
operator, which masks the count to the width (U32 1 « 33 read 2). A shift in a predeclared type’s context took
golib’s guard, which follows Go; this one did not.
Fix. Re-convert with a go2cs release after 1.26.11.1. The shift takes golib’s guard of the underlying type and
converts the result to the named type: (U32)(((uint32)1).Lsh(s)).
Workaround. Give the constant the named type yourself, U32(1) << s. A typed operand shifts through the named
type’s own operator, which follows Go.
With go2cs 1.26.10.2 or earlier, a program converted with local standard-library references runs its standard library built Debug
Symptom. A program converted by go2cs 1.26.10.2 or earlier with plain -recurse or -recurse=module
references the standard library as local projects. Built with dotnet build -c Release in its folder, its
standard-library assemblies come out built Debug, unoptimized, and it runs slower than the same program built from
its .csproj (about 21 times slower on a TLS handshake under the JIT, on win-x64, on one development machine).
dotnet publish -c Release -r <rid> in the folder can fail with
ILLink : error IL1034: Root assembly 'golib' ... does not have entry point, and when it succeeds the published
program carries the same Debug assemblies. A -recurse=nuget conversion is not affected.
Cause. The converter wrote a .slnx beside each project, and in a folder that holds both, dotnet build and
dotnet publish take the solution. A solution build gives its configuration only to the projects the solution
lists, which were the program, golib and the analyzer, so every other standard-library project it built took its
default configuration, Debug. Publishing the solution also published golib as a project of its own.
Fix. Re-convert with go2cs 1.26.10.3 or later. It writes no solution for a local-reference conversion, and it removes the one an earlier converter wrote, if that file is unchanged.
Workaround. Build or publish the project, not a solution: run the command in a folder that holds no .sln
or .slnx, or name the .csproj (dotnet build <app>.csproj -c Release). Do not build these conversions through
a solution: the core projects a solution does not list build Debug. In Visual Studio, open the .csproj.
With the go.* 1.26.10.1 packages, a Native AOT program that uses the network can exit with an error
Symptom. A Native AOT executable (PublishAot) that references the go.* 1.26.10.1 packages exits with code 2
the first time it passes a pointer to certain Go structs to a system call. It prints
System.NotSupportedException: 'System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences[System.UInt16]()' is missing native code
(the type in brackets varies). On Windows, a program that uses net or crypto/tls reaches it while setting up a
socket, in syscall.WSAIoctl. On Linux and macOS, the same system-call marshalling runs for a pointer to a struct that
holds a pointer, slice, string or array, and fails the same way. The same program run under the JIT (dotnet run, or
the converted project’s default ReadyToRun publish) is not affected. Measured on win-x64, linux-x64 and osx-arm64.
Cause. The runtime library’s system-call marshalling sorted a struct’s fields with a generic method it closed at run time, and a Native AOT image has no code for such a method.
Fix. Move to the go.* 1.26.10.2 packages or later.
Workaround on 1.26.10.1. Publish without Native AOT: the converted project’s default dotnet publish (ReadyToRun) and a
framework-dependent build run the same code under the JIT.
With the go.* 1.24.13.7 packages or earlier, a Native AOT publish can take hours or not finish
Symptom. A Native AOT publish (PublishAot) of a program that references the go.* 1.24.13.7 packages, or an
earlier release, does not finish or takes hours. The ILC compiler holds about 14 GB of memory and prints tens of
thousands of warnings that a method will always throw because a type from golib failed to load. Measured on
win-x64, on one development machine.
Cause. These releases were built before the fix to the runtime library’s generic cycle (see the Native AOT section). Native AOT expands that cycle until it reaches its nesting limit, and compiles each method that reaches past the limit to throw, which is what those warnings report.
Fix. Move to the go.* 1.26.10.1 packages or later. They carry the fix, and the 1.24.13.7 packages’ deprecation
notice already points to them.
Workaround on 1.24.13.7. Turn off identical-method folding in the project file:
<IlcFoldIdenticalMethodBodies>false</IlcFoldIdenticalMethodBodies>
The publish then finishes for most programs, at a cost: ILC peaked at about 28 GB, and the executable was 3.3 times
the size of the same program built against 1.26.10.1. A very large program can still fail at link (LNK1183,
“extended relocation count 9 less than 65535”) when the compiler’s object file passes 4 GiB, the COFF object
format’s limit, and the workaround has nothing more to offer it: move to 1.26.10.1. Measured on win-x64: every program
of the performance suite but the TLS handshake published this way; that one failed at link.