douzi2778 2019-09-17 16:29
浏览 34

如何不使用新方法初始化结构变量net.Conn

loadtest/src/client/client.go

import (
    "fmt"
    "net"
    "bufio"
    "log"
)

type Client struct {
    Conn    net.Conn
    Err     error
}

func (e Client) SetConnection(ServerAddr string){
    e.Conn, e.Err = net.Dial("tcp", ServerAddr)
    if e.Err != nil {
        log.Fatalf("Fail to connect to Server")
    }
}

func (e Client) MakeRequest(Message string){
    e.Conn.Write([]byte(Message))
}

func (e Client) ListenResponse() {
    message, _ := bufio.NewReader(e.Conn).ReadString('}')
    fmt.Print("Message from server: " + message + "
")
}

loadtest/src/main/main.go

package main
import (
    "client"
)

func main() {
    e:=client.Client{}
    e.SetConnection("192.168.0.1:3999")
    e.MakeRequest("login_req") //panic: runtime error: invalid memory address or nil pointer dereference
    e.ListenResponse()
}

I use above code to create and initialize the Client. But when the MakeRequest is called, It print runtime errors invalid memory address or nil pointer dereference, and it noticed me e.Conn is "nil" and e.Err is also "nil".

I want to initialize instance of the struct 'Client' with SetConnection. How can I do that?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号