golang 在go中注册堆栈实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 在go中注册堆栈实现相关的知识,希望对你有一定的参考价值。

package main
//go program to implement a portable VM

import (
    "fmt"
    "reflect"
)

type RegisterStack struct {
	registers map[int]interface{}
	
	//stores records of amount of registers and locations
	records map[string]int
}

//creates a new register set
func CreateRStk() RegisterStack {
	rs := RegisterStack{registers:make(map[int]interface{}), records:map[string]int{"last":-1, "next":0}}
	return rs
}
//initializes a new register space
func (rs RegisterStack) Addregister() {
	rs.registers[rs.records["next"]] = nil
	rs.records["last"] += 1
	rs.records["next"] += 1
}

//deletes the last register in the stack
func (rs RegisterStack) Removeregister() {
	delete(rs.registers, rs.records["last"])
	rs.records["last"] -= 1
	rs.records["next"] -= 1
}
//sets a value to a register
func (rs RegisterStack) SetValue(val interface{}, register int) {
	if register >= 0 && register < rs.records["next"] {
		rs.registers[register] = val
	}
}
//gets a value from a register
func (rs RegisterStack) GetValue(register int) interface{} {
	return rs.registers[register]
}




func main(){
	vartest := CreateRStk()
	vartest.Addregister()
	vartest.Addregister()
	vartest.SetValue("foo", 0)
	vartest.SetValue(3, 1)
	//type assertion
	extract := vartest.GetValue(1).(int)
	extract += 2
	vartest.SetValue(extract, 1)
	fmt.Println(reflect.TypeOf(extract))
	fmt.Println(vartest)
}

golang go lang中的可扩展注册机

package main

import "fmt"

//multitype of register slot in virtual machin
type register struct {
	i int
	b bool
	s string
}


func main() {
	table := make([]register, 10)
	table[0].s += "hello"
	table[1].i += 5
  fmt.Println(table)
  /*[{0 false hello} {5 false } {0 false } {0 false } {0 false } {0 false } {0 false } {0 false } {0 false } {0 false }]*/
}

以上是关于golang 在go中注册堆栈实现的主要内容,如果未能解决你的问题,请参考以下文章

Golang教程:goroutine协程

Golang Go语言中的 defer 怎么使用?

golang go lang中的可扩展注册机

Golang内部构件,第5部分:运行时引导程序

如何看待go语言泛型的最新设计?

go语言实现一个简单的登录注册web小程序