incu6us / goimports-reviser

Right imports sorting & code formatting tool (goimports alternative)
MIT License
611 stars 72 forks source link

Incorrect behavior with cgo when only import "C" is used #156

Open kokororin opened 6 months ago

kokororin commented 6 months ago

When using cgo, the behavior can be incorrect if there is only an import "C" statement in the Go file.

Before:

package demo

/*
#include <stdlib.h>
#include "version.h"
*/
import "C"

// Version returns version string
func Version() string {
    return C.GoString(C.version())
}

After:

package demo

import "C"

func Version() string {
    return C.GoString(C.version())
}

One workaround for this issue is to add an underscore import after import "C". This ensures the correct behavior. Here is the modified code:

package demo

/*
#include <stdlib.h>
#include "version.h"
*/
import "C"
import (
    _ "fmt"
)

// Version returns version string
func Version() string {
    return C.GoString(C.version())
}