dppxp79175 2017-02-26 01:33
浏览 54
已采纳

两个字符串具有相同的指针地址

Why is this so? Here's my code:

import (
    "database/sql"
    "fmt"
    "reflect"        

    "github.com/fatih/structs"
)

type UserLogin struct {
    Username string
    Password string
}

func Login() {
    row := sql.QueryRow("SELECT username, password FROM users WHERE username=?", "golang")

    userLoginKeys := structs.Names(UserLogin{})
    keys := make([]interface{}, len(userLoginKeys), len(userLoginKeys))
    for i, val := range userLoginKeys {
        keys[i] = &val
        fmt.Println(val)
    }

    fmt.Println(keys)

    _ := row.Scan(keys...)
    v1 := reflect.ValueOf(keys[0]).Elem().String()
    v2 := reflect.ValueOf(keys[1]).Elem().String()
    fmt.Println(v1)
    fmt.Println(v2)
}

It prints

Username
Password
[0xc4201ca2c0 0xc4201ca2c0] 
$2a$10$F6hR0scvtbFDx0l1GR.OX.ZweozUzwKVTG3H8GBQxpYCEdFifDrzy
$2a$10$F6hR0scvtbFDx0l1GR.OX.ZweozUzwKVTG3H8GBQxpYCEdFifDrzy

As you can see, keys contains the same address to two different strings. As a result, their values are the same.

My goal is to map username and password to UserLogin struct.

  • 写回答

3条回答 默认 最新

  • dqalnwuci494308 2017-02-26 02:27
    关注

    Change keys[i] = &val to keys[i] = &userLoginKeys[i], so you can get different addresses.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?