Go编程语言规范说.
如果所有字段都具有可比性,则结构值可比较.如果相应的非空白字段相等,则两个结构值相等.
但是,如下面的代码片段,它似乎是变量v1,并且v3具有不同的类型,为什么它们可以获得真正的输出:
package main
import "fmt"
import "reflect"
type T1 struct { name string }
type T2 struct { name string }
func main() {
v1 := T1 { "foo" }
v2 := T2 { "foo" }
v3 := struct{ name string } {"foo"}
v4 := struct{ name string } {"foo"}
fmt.Println("v1: type=", reflect.TypeOf(v1), "value=", reflect.ValueOf(v1)) // v1: type= main.T1 value= {foo}
fmt.Println("v2: type=", reflect.TypeOf(v2), "value=", reflect.ValueOf(v2)) // v2: type= main.T2 value= {foo}
fmt.Println("v3: type=", reflect.TypeOf(v3), "value=", …Run Code Online (Sandbox Code Playgroud) 我在new运算符中使用c ++常量值std :: nothrow以避免失败时出现异常,并返回null.但是,正如我所尝试的那样,在我的环境中,这似乎不适用于Linux x86_64上的g ++ 4.4.4.
以下是测试程序和执行结果:
#include <stdlib.h>
#include <new>
#include <iostream>
class TT {
public:
TT(int size);
~TT();
private:
char * buffer;
};
TT::TT(int size) : buffer(NULL) {
if (size <= 0) {
throw std::bad_alloc();
}
buffer = (char *)malloc(size);
if (buffer == NULL) {
throw std::bad_alloc();
}
}
TT::~TT() {
if (buffer != NULL) {
delete buffer;
}
}
int main(int argc, char * argv[]) {
TT * tt = NULL;
try {
tt = new …Run Code Online (Sandbox Code Playgroud) 如何调用未导出的包函数,例如包函数hello()定义为:
package testlib
import "fmt"
func hello() {
fmt.Println("Hello testlib")
}
Run Code Online (Sandbox Code Playgroud)
并且主要包裹有来电:
package main
import (
_ "reflect"
"testlib"
)
func main() {
testlib.hello()
}
Run Code Online (Sandbox Code Playgroud)
当然,这个程序是不正确的.我google了很多,很多人提到反射包可以用来调用一个未导出的函数,如:
obj := ... (some object)
val := reflect.ValueOf(obj);
fun := val.MethodByName("hello")
fun.Call([]reflect.Value{})
Run Code Online (Sandbox Code Playgroud)
但是所有示例都基于对象(即结构),而不是包.我的问题是我要调用一个包函数,而不是一个对象函数.谢谢.