我使用github.com/lib/pq将Go与PostgreSQL一起使用。
我想opendb()在其他函数中调用此函数,但是返回值有问题。
package database
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "pgpassword"
dbname = "postgres"
)
func opendb() (*DB) {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s " +
"sslmode=disable", host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
return db
}
Run Code Online (Sandbox Code Playgroud)
如果运行此命令:
$ go run main.go
Run Code Online (Sandbox Code Playgroud)
它将显示此错误:
error:
undefined: DB
Run Code Online (Sandbox Code Playgroud) 我使用这个库golang.org/x/crypto/bcrypt来散列密码并将散列与密码进行比较,但我遇到了问题,见下文:
main.go 文件
package main
import (
"./hash"
)
func main() {
password := "passwd"
hash := "hhhhhhhhaaaaaaaaaassssssssssshhhhhhhhhhh"
check := hash.CheckPasswordHash(password, hash)
}
Run Code Online (Sandbox Code Playgroud)
hash/hash.go 文件
package hash
import "golang.org/x/crypto/bcrypt"
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
Run Code Online (Sandbox Code Playgroud)
如果你运行这个:
$ go run main.go
Run Code Online (Sandbox Code Playgroud)
它会显示这个错误:
./main.go:11:15: hash.CheckPasswordHash undefined(字符串类型没有字段或方法CheckPasswordHash)
为什么这个错误?
当我将结构传递给函数时,我得到错误:期望'struct book'但是参数是'struct book'类型.为什么会这样?
#include <stdio.h>
#include <string.h>
struct book
{
int id;
char title[50];
};
int showBooks(struct book x);
int main()
{
struct book
{
int id;
char title[50];
};
struct book book1,book2;
book1.id = 2;
book2.id = 3;
strcpy(book1.title, "c programming");
strcpy(book2.title, "libc refrence");
printf("Book\t\tID\n");
showBooks(book1);
showBooks(book2);
}
int showBooks(struct book x)
{
printf("%s\t%d\n", x.title, x.id);
}
Run Code Online (Sandbox Code Playgroud)
错误:
30:12:错误:"showBooks"
showBooks(book1)的参数1的不兼容类型;10:5:注意:预期的'struct book'但是参数类型为'struct book'int showBooks(struct book x);
31:12:错误:"showBooks"
showBooks(book2)的参数1的不兼容类型;10:5:注意:预期的'struct book'但是参数类型为'struct book'int showBooks(struct book x);
这里的错误在哪里?