Golang:函数返回参数错误

huangapple go评论87阅读模式
英文:

Golang: function return argument error

问题

以下代码给出了:

runtime.main: 调用外部函数 main.main
runtime.main: main.main: 未定义
runtime.main: 未定义: main.main

我弄错了返回参数,但是为什么?

请求:

fmt.Println(reflect.TypeOf(l))

返回 *ldap.Conn 作为类型

在不尝试返回对象的情况下,代码可以正常工作

package main
    
import (
	"fmt"
	"log"

	"gopkg.in/ldap.v2"
)


var Ldap1 = "10.0.0.1"
var Lport1 = 389
var Prpl1 = "cn=admin,dc=Example,dc=com"
var Pass1 = "password"
    
func Bindldap(ldaphost string, port int, principal string, password string) *ldap.Conn {

	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldaphost, port))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	err = l.Bind(principal, password)
	if err != nil {
		log.Fatal(err)
	}
	return l
}

func Main() {
	a := Bindldap(Ldap1, Lport1, Prpl1, Pass1)
	//对a进行一些操作
}
英文:

The following code gives:

runtime.main: call to external function main.main
runtime.main: main.main: not defined
runtime.main: undefined: main.main

I messed up with the return argument, but why?

Requesting:

fmt.Println( reflect.TypeOf(l)) 

gives *ldap.Conn as type

The code works without trying to return the object

package main
    
import (
	"fmt"
	"log"

	"gopkg.in/ldap.v2"
)


var Ldap1 = "10.0.0.1"
var Lport1 = 389
var Prpl1 = "cn=admin,dc=Example,dc=com"
var Pass1 = "password"
    
func Bindldap(ldaphost string, port int, principal string, password string) *ldap.Conn {

	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldaphost, port))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	err = l.Bind(principal, password)
	if err != nil {
		log.Fatal(err)
	}
	return l
}

func Main() {
	a := Bindldap(Ldap1, Lport1, Prpl1, Pass1)
	//do something with a
}

答案1

得分: 2

你的错误信息告诉你它正在寻找名为main的函数,而你在main包中调用了你的入口点Main(注意大写)。尝试使用以下代码:

func main() {
    a := Bindldap(Ldap1, Lport1, Prpl1, Pass1)
    //对a进行操作
}
英文:

You error messages are telling you it's looking for a function called main in your main package. You called your entry point Main (Note the caps). Try this:

func main() {
    a := Bindldap(Ldap1, Lport1, Prpl1, Pass1)
    //do something with a
}

huangapple
  • 本文由 发表于 2017年5月10日 23:26:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/43896821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定